#1108
Defanging an IP Address
Easy StringBuilder
- Read
- Understand
- Hints
- Approach
- Solution
- Solved
?The problem
Replace every "." in an IPv4 address with "[.]".
This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗
◎Understanding
Really asking: rewrite the address with every "." turned into "[.]".
Why this works: StringBuilder lets you append piece by piece in O(n). Adding to a String with + inside a loop copies the whole string each time.
Example: "1.1.1.1"
'1' → "1"'.' → "1[.]"… → "1[.]1[.]1[.]1"
✦Hints open one at a time
Strings in Java are immutable — building a new one with + in a loop creates many copies.
Use a StringBuilder and append character by character.
↗Approach
Walk through the characters; append "[.]" for a dot and the character otherwise. StringBuilder keeps this O(n). (address.replace(".", "[.]") also works and is fine in an interview if you can explain it.)
</>Solution (Java)
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();
}
}
!Common mistake
Using replaceAll(".", ...) — replaceAll takes a regex, and "." matches every character.
Complexity
- Time: O(n).
- Space: O(n) for the result.
