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:
address
is a valid IPv4 address.This problem asks to replace every occurrence of a period (.
) in an IPv4 address string with [.]
. The most efficient approach leverages built-in string manipulation functions available in most programming languages.
The core idea is to directly substitute all occurrences of "." with "[.]" within the input string. This avoids the need for character-by-character processing, making the solution concise and highly efficient.
Time Complexity: O(n), where n is the length of the input string. The replace()
function (or its equivalent in other languages) typically has a linear time complexity because it needs to iterate through the string once.
Space Complexity: O(n) in the worst case. This is because the defanged IP address string could be at most slightly longer than the original string (if all characters are periods) requiring additional space for the result. However, if we ignore the space used for the output, the space complexity is considered O(1) as only a constant amount of extra space is needed.
The following code snippets demonstrate the solution in several programming languages, highlighting the simplicity of the direct replacement approach:
Python3:
class Solution:
def defangIPaddr(self, address: str) -> str:
return address.replace('.', '[.]')
Python's replace()
method directly handles the substitution.
Java:
class Solution {
public String defangIPaddr(String address) {
return address.replace(".", "[.]");
}
}
Java's replace()
method functions similarly to Python's.
C++:
class Solution {
public:
string defangIPaddr(string address) {
return address.replace('.', "[.]");
}
};
C++'s replace()
method also provides a straightforward solution.
Go:
func defangIPaddr(address string) string {
return strings.Replace(address, ".", "[.]", -1)
}
Go's strings.Replace()
replaces all occurrences. The -1
as the final argument signifies replacing all instances.
TypeScript:
function defangIPaddr(address: string): string {
return address.split('.').join('[.]');
}
This TypeScript solution uses split()
to separate the string at each period and join()
to reassemble it with "[.]" as the separator. While functional, it might be slightly less efficient than a direct replacement for very large strings.
All these implementations showcase the core concept of using a built-in string replacement function for optimal efficiency. The choice of language affects only the syntax, not the underlying algorithmic approach.