【LeetCode】【String】defanging an IP address
【题目】
给定有效的(IPv4)IP地址,请返回该IP地址的脱机版本。新的IP地址将替换每个句点“.” 与“ [.]”。
Example 1:
Input: address = "1.1.1.1" Output: "1[.]1[.]1[.]1"
Example 2:
Input: address = "255.100.50.0" Output: "255[.]100[.]50[.]0"
Constraints:
- The given
addressis a valid IPv4 address.
【解法一】
class Solution: def defangIPaddr(self, address: str) -> str: new = "" for i in address: if i == ".": new = new + '[.]' else: new = new + i return new
Runtime: 28 ms, faster than 73.31% of Python3 online submissions for Defanging an IP Address.
Memory Usage: 13.7 MB, less than 80.59% of Python3 online submissions for Defanging an IP Address.
【解法】
将"."替换成“[.]”
class Solution: def defangIPaddr(self, address: str) -> str: ip = address.split(".") new = [0]*(len(ip)-1) for i in range(0,len(ip)-1): new[i] = ip[i]+"[.]" new.append(ip[-1]) return "".join(new)
Runtime: 28 ms, faster than 73.31% of Python3 online submissions for Defanging an IP Address.
Memory Usage: 14 MB, less than 5.10% of Python3 online submissions for Defanging an IP Address.
【解法】
简洁,一句话概括上面的两种解法。
def defangIPaddr(self, address: str) -> str: return address.replace('.', '[.]') def defangIPaddr(self, address: str) -> str: return '[.]'.join(address.split('.')) def defangIPaddr(self, address: str) -> str: return re.sub('\.', '[.]', address) #快 def defangIPaddr(self, address: str) -> str: return ''.join('[.]' if c == '.' else c for c in address) #快,且内存占用少
Runtime: 32 ms, faster than 45.10% of Python3 online submissions for Defanging an IP Address.
Memory Usage: 13.8 MB, less than 50.10% of Python3 online submissions for Defanging an IP Address.
Runtime: 32 ms, faster than 45.10% of Python3 online submissions for Defanging an IP Address.
Memory Usage: 13.8 MB, less than 43.74% of Python3 online submissions for Defanging an IP Address.
Runtime: 24 ms, faster than 91.51% of Python3 online submissions for Defanging an IP Address.
Memory Usage: 13.8 MB, less than 55.07% of Python3 online submissions for Defanging an IP Address.
Runtime: 24 ms, faster than 91.51% of Python3 online submissions for Defanging an IP Address.
Memory Usage: 13.7 MB, less than 84.40% of Python3 online submissions for Defanging an IP Address.
【Python 函数】replace()方法
Python replace() 方法把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次。
replace()方法语法:str.replace(old, new[, max])
关于 string 的 replace 方法,需要注意 replace 不会改变原 string 的内容。
实例:
temp_str = 'this is a test'
print(temp_str.replace('is','IS')
print(temp_str)
结果为:
thIS IS a test
this is a test

浙公网安备 33010602011771号