Skip to content

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.

Solutions

Solution 1: Direct Replacement

We can directly replace the '.' in the string with '[.]'.

The time complexity is $O(n)$, where $n$ is the length of the string. Ignoring the space consumption of the answer, the space complexity is $O(1)$.

1
2
3
class Solution:
    def defangIPaddr(self, address: str) -> str:
        return address.replace('.', '[.]')
1
2
3
4
5
class Solution {
    public String defangIPaddr(String address) {
        return address.replace(".", "[.]");
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution {
public:
    string defangIPaddr(string address) {
        for (int i = address.size(); i >= 0; --i) {
            if (address[i] == '.') {
                address.replace(i, 1, "[.]");
            }
        }
        return address;
    }
};
1
2
3
func defangIPaddr(address string) string {
    return strings.Replace(address, ".", "[.]", -1)
}
1
2
3
function defangIPaddr(address: string): string {
    return address.split('.').join('[.]');
}

Comments