Problem# Given a valid (IPv4) IP address, return a defanged version of that IP address.
A defanged IP address replaces every period "." with "[.]".
Examples# Example 1# 1
2
Input: address = "1.1.1.1"
Output: "1[.]1[.]1[.]1"
Example 2# 1
2
Input: address = "255.100.50.0"
Output: "255[.]100[.]50[.]0"
Constraints# The given address is a valid IPv4 address. Solution# Method 1 – String Replacement# Intuition# The problem is a simple string manipulation: replace every period . in the IP address with [.]. This can be done efficiently using built-in string replacement functions in most languages.
Approach# Iterate through the string and replace every . with [.]. Return the modified string. Code#
Cpp
Go
Java
Kotlin
Python
Rust
Typescript
1
2
3
4
5
6
7
8
9
10
11
class Solution {
public :
string defangIPaddr(string address) {
string ans;
for (char c : address) {
if (c == '.' ) ans += "[.]" ;
else ans += c;
}
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
11
func defangIPaddr (address string ) string {
ans := ""
for _ , c := range address {
if c == '.' {
ans += "[.]"
} else {
ans += string(c )
}
}
return ans
}
1
2
3
4
5
class Solution {
public String defangIPaddr (String address) {
return address.replace ("." , "[.]" );
}
}
1
2
3
4
5
class Solution {
fun defangIPaddr (address: String): String {
return address.replace("." , "[.]" )
}
}
1
2
3
class Solution :
def defangIPaddr (self, address: str) -> str:
return address. replace('.' , '[.]' )
1
2
3
4
5
impl Solution {
pub fn defang_i_paddr (address: String) -> String {
address.replace("." , "[.]" )
}
}
1
2
3
4
5
class Solution {
defangIPaddr (address : string ): string {
return address .replace (/\./g , '[.]' );
}
}
Complexity# ⏰ Time complexity: O(n), where n is the length of the address, since we scan each character once. 🧺 Space complexity: O(n), for the output string.