Given a valid (IPv4) IP address
, return a defanged version of that IP address.
A defanged IP address replaces every period .
with [.]
.
Input:
address = "1.1.1.1"
Output:
"1[.]1[.]1[.]1"
To solve this problem, we simply need to replace all occurrences of the period character .
with [.]
.
Python’s string replace
method is ideal for this task, as it allows direct replacement of substrings in a straightforward and efficient manner.
replace
method on the input string address
to replace all .
with [.]
.def defangIPaddr(address: str) -> str:
# Replace all occurrences of '.' with '[.]'
return address.replace('.', '[.]')
The time complexity of the solution is O(n)
, where n
is the length of the input string, because the replace
method needs to traverse the string to replace each occurrence of .
.
O(n)
O(1)
additional space (the space for the new string is not counted as additional space).This approach is both time-efficient and space-efficient for the given problem constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?