Given a valid (IPv4) IP address
, return a defanged version of that IP address.
A defanged IP address replaces every period "."
with "[.]"
.
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
address
is a valid IPv4 address.
------------------------------------------------------------------------------------------------------------------------------------------------
Approach #1 我的解法 string.split():
class Solution {
public String defangIPaddr(String address) {
String[] stringSplit = address.split("\\.");
String defang = "[.]";
String ans = "";
int len = stringSplit.length;
for(int i=0;i<len-1;i++) {
ans += stringSplit[i];
ans += defang;
}
ans +=stringSplit[len-1];
return ans;
}
}
分析:
我的解法十分的笨拙,又慢又占内存。
时间复杂度O(2 * address.length)
空间复杂度O(stringSplit.length+defang.length)
知识点:
string.split(regx): 需要传入正则表达式,注意对“.", 要用转义字符”\\.“
Approach #2 String Builder
public String defangIPaddr(String address) {
StringBuilder str = new StringBuilder();
for(int i = 0; i < address.length(); i++) {
if(address.charAt(i) == '.'){
str.append("[.]");
} else {
str.append(address.charAt(i));
}
}
return str.toString();
}
分析:
时间复杂度:O(address.length)
空间复杂度:O(str.length)
知识点:
1. string.charAt(int index): 可以读取string在第i个位置的元素
2. 使用StringBuilder str = new StringBuilder,
str.append(String) 来构建一个String