Defanging an IP Address
EASYDescription
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
addressis a valid IPv4 address.
Approaches
Checkout 3 different approaches to solve Defanging an IP Address. Click on different approaches to view the approach and algorithm in detail.
Approach 2: Iteration with StringBuilder
This approach involves manually iterating through the input string character by character and building the result using a StringBuilder. A StringBuilder is chosen for its efficiency in string manipulation, as it avoids creating a new string object for every concatenation.
Algorithm
- Initialize a new
StringBuilder. - Iterate through each character of the input
addressstring. - If the current character is a
.(period), append the string"[.]"to theStringBuilder. - Otherwise, append the character itself.
- After the loop completes, convert the
StringBuilderto a string and return it.
This method provides direct control over the string construction process.
- We create an empty
StringBuilderinstance, let's call itsb. - We loop through the input
addressstring. For each characterc: - We check if
cis equal to'.'. - If it is, we append the replacement string
"[.]"tosb. - If it's not a period, we simply append the character
ctosb. - Once the loop has processed all characters in the address, the
sbcontains the defanged version. We callsb.toString()to get the final string and return it.
class Solution {
public String defangIPaddr(String address) {
StringBuilder sb = new StringBuilder();
for (char c : address.toCharArray()) {
if (c == '.') {
sb.append("[.]");
} else {
sb.append(c);
}
}
return sb.toString();
}
}
Complexity Analysis
Pros and Cons
- Highly efficient in terms of performance, as it involves a single pass through the string.
- Avoids the overhead of regular expressions and creating intermediate data structures like arrays.
- Memory usage is optimized by using a mutable
StringBuilder.
- The code is more verbose than using a built-in
replacemethod. - Requires manual implementation of the iteration and replacement logic.
Code Solutions
Checking out 3 solutions in different languages for Defanging an IP Address. Click on different languages to view the code.
class Solution {
public
String defangIPaddr(String address) { return address.replace(".", "[.]"); }
}
Video Solution
Watch the video walkthrough for Defanging an IP Address
Similar Questions
5 related questions you might find useful
Data Structures:
Companies:
Subscribe to Scale Engineer newsletter
Learn about System Design, Software Engineering, and interview experiences every week.
No spam, unsubscribe at any time.