Table of Contents
Problem Statement
Defanging an IP Address LeetCode Solution – 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"
Explanation
The intuition is very simple.
1. create a Stringbuilder str
2. loop through the address string and check for char ‘.’.
3. For each character in the string. If the character is ‘.” then append “[.]” to the string builder. Else append the same character to string builder.
4. Convert the stream/builder to string and return it.
Replace Every Occurrence of . with [.] by using replace Method of String.
Replace method will not change the Original String Because Strings are Immutable in JAVA
So, it will return a New Object. Store that Object in String result and at the end just return the result.
Just need to use the replace function to get the desired output.
Code
C++ Code for Defanging an IP Address
class Solution { public: string defangIPaddr(string address) { return regex_replace(address, regex("[.]"), "[.]"); } };
Java Code for Defanging an IP Address
class Solution { public String defangIPaddr(String address) { return address.replace(".","[.]"); } }
Python Code for Defanging an IP Address
class Solution: def defangIPaddr(self, address: str) -> str: return address.replace('.', '[.]')
Complexity Analysis for Defanging an IP Address LeetCode Solution
Time Complexity
O(n) since we are traversing the given string linearly, Thus it’s O(n).
Space Complexity
O(1) but basically Space complexity will also depend upon the internal implementation of the pre-defined functions.