1108. Defanging an IP Address
作者:互联网
1108. Defanging an IP Address
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"
分析:
题目的目的就是将一个字符串里的字符.
替换为[.]
。
方法1
- 创建一个空字符
ans
作为答案; - 遍历
address
,如果字符是.
,就在ans
后追加[.]
,否则就追加该字符; - 返回
ans
;
class Solution {
public String defangIPaddr(String address) {
char[] chars = address.toCharArray();
StringBuilder stringbuilder = new StringBuilder();
for (char c : chars) {
if (c == '.') {
stringbuilder.append("[.]");
} else {
stringbuilder.append(c);
}
}
return stringbuilder.toString();
}
}
方法2
使用子串的方法,根据.
的位置获取子字符串,并替换.
为[.]
,再使用字符串连接即可;
class Solution {
public String defangIPaddr(String address) {
for (int i = 0; i < address.length(); i++) {
if (address.charAt(i) == '.') {
address = address.substring(0, i) + "[.]" + address.substring(i + 1);
i += 2;
}
}
return address;
}
}
标签:字符,Defanging,String,IP,address,ans,stringbuilder,字符串,1108 来源: https://www.cnblogs.com/zhuobo/p/11257113.html