algoadvance

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

  1. Input Format: Is the input guaranteed to be a valid IPv4 address?
    • Answer: Yes, the input is guaranteed to be a valid IPv4 address.
  2. 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

  1. String Replacement: Use the replace method to replace all occurrences of “.” with “[.]”.
  2. 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

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