[LeetCode] 1108. Defanging an IP Address
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
address
is a valid IPv4 address.
Analyse
将ip地址中的.
替换成[.]
, 简单题
在address上直接replace,或者插入到一个新的字符串里去
string defangIPaddr(string address)
{
for(int i = 0; i < address.size(); i++)
{
if (address[i] == '.')
{
address.replace(i, 1, "[.]");
i+=2; //使i越过已经replace过的 .
}
}
cout << address << endl;
return address;
}
string defangIPaddr(string address)
{
string result;
for(int i = 0; i < address.length(); i++)
{
if (address[i] == '.')
{
result += "[.]";
}
else
{
result += address[i];
}
}
return result;
}