1108. Defanging an IP Address
1108. Defanging an IP Address
题目
Given a valid (IPv4) IP
address, return a defanged version of that IP address.A defanged IP address replaces every period
"."with"[.]".Example 1:
1
2 Input: address = "1.1.1.1"
Output: "1[.]1[.]1[.]1"Example 2:
1
2 Input: address = "255.100.50.0"
Output: "255[.]100[.]50[.]0"Constraints:
- The given
addressis a valid IPv4 address.
解题
很简单的一道题,字符串的替换。
第一次尝试:最开始没有想起replace方法,用了笨办法(split方法)
1 | class Solution(object): |
更好的答案:
1 | class Solution(object): |
总结
- 这里弄混了split和strip方法,特此总结:
Python strip() 方法用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列。
1 | str.strip([chars]) |
Python split() 通过指定分隔符对字符串进行切片,如果参数num有指定值,则分隔num+1个子字符串(num表示分割次数)
1 | str.split(str="", num=string.count(str)) |
这里也可以用split方法与str.join(sequence)方法拼接获得结果。
- 任何可以用 for 循环c遍历的东西都是可迭代的。python的字符串也是可迭代的。所以有:
1 | str = '1.1.1.1' |
结果为:
1 | 1 |
- 每一种语言都有相应的字符串替换函数,如:
C++中可以用regex_replace(address, regex("[.]"), "[.]");
JAVA中可以用address.replace(".", "[.]");或者String.join("[.]", address.split("\\."));