Featured image of post Defanging an IP Address

Defanging an IP Address

1108. IP地址无效化

分析

  1. 遍历字符串,逐个检查字符
  2. 如果是 '.' ,就将其替换为 "[.]"
  3. 否则,直接添加到新字符串中

时间复杂度

时间复杂度为 O(n)

空间复杂度

空间复杂度为 O(n)

C++代码

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution
{
public:
    string defangIPaddr(string address)
    {
      std::string res;  // 存储转换后的字符串
      for (char c : address)   // 遍历输入字符串
        if (c == '.')
          res += "[.]";  // 遇到 '.' 时替换为 "[.]"
        else
          res += c;  // 其他字符直接加入结果字符串
      return res;
    }
};
Built with Hugo
Theme Stack designed by Jimmy