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.
這道題給了一個 IP 地址,讓把其中的點都換成用中括號包起來的點,這種字符替換的問題,用 Java 的話可以說是太方便了,各種函數可以調用,比如 replace, join, replaceAll 等等,好用的飛起。但是很可惜博主是用的 C++,所以用不了這些函數,而是要是用字符串流類,將給定的字符串根據點的位置分開,並把每段字符串提取出來,然后加到結果 res 之后,並加上 [.]
,這種最終會多加一個中括號,別忘移除掉即可,參見代碼如下:
解法一:
class Solution {
public:
string defangIPaddr(string address) {
string res, t;
istringstream is(address);
while (getline(is, t, '.')) {
res += t + "[.]";
}
return res.substr(0, (int)res.size() - 3);
}
};
其實不用字符串流類也可以,就是直接遍歷原字符串,遇到點了,就直接把 [.]
加入,否則就加入當前字符即可,參見代碼如下:
解法二:
class Solution {
public:
string defangIPaddr(string address) {
string res;
for (char c : address) {
if (c == '.') res += "[.]";
else res += c;
}
return res;
}
};
雖然前面提到了 C++ 中沒有很強大的字符串替換的方法,但是這里也可以用 regex_replace 來直接進行替換,一行搞定碉堡了有木有,參見代碼如下:
解法三:
class Solution {
public:
string defangIPaddr(string address) {
return regex_replace(address, regex("[.]"), "[.]");
}
};
Github 同步地址:
https://github.com/grandyang/leetcode/issues/1108
參考資料:
https://leetcode.com/problems/defanging-an-ip-address/
https://leetcode.com/problems/defanging-an-ip-address/discuss/328855/C%2B%2B-1-liner-(regex_replace)