Leetcode 1108. Defanging an IP Address
Problem Statement
Given a valid (IPv4) IP address, return a defanged version of that IP address. A defanged IP address replaces every period “.” with “[.]”.
Clarifying Questions
- Input Format: Is the input guaranteed to be a valid IPv4 address?
- Answer: Yes, the input is guaranteed to be a valid IPv4 address.
- Length of Input: Is there a maximum length for the IP address string?
- Answer: A valid IPv4 address is formatted as four decimal numbers separated by periods, where each number can be from 0 to 255. The maximum length is 15 characters (e.g., “255.255.255.255”).
Strategy
- String Replacement: Use the
replace
method to replace all occurrences of “.” with “[.]”.
- Efficiency: This approach is straightforward and efficient, as string replacement is a single-pass operation.
Code
public class Solution {
public String defangIPaddr(String address) {
return address.replace(".", "[.]");
}
}
Time Complexity
- Time Complexity: O(n), where n is the length of the input string. The
replace
method will process each character in the string once.
- Space Complexity: O(n), where n is the length of the input string. The new string created by
replace
will have almost the same length as the input string, slightly more due to the inclusion of brackets.
This completes our approach to solving the problem of defanging an IP address!
Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI
-
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?