Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork739
Description
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
addressis 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://leetcode.com/problems/defanging-an-ip-address/
https://leetcode.com/problems/defanging-an-ip-address/discuss/328855/C%2B%2B-1-liner-(regex_replace)