algoadvance

Leetcode 1108. Defanging an IP Address

Problem Statement

You are given a valid IPv4 address address. Return a defanged version of that IP address.

A defanged IP address replaces every period . with [.].

Clarifying Questions

Before we jump into solving the problem, let’s ensure we understand all the requirements and constraints:

  1. Input: What is the form of the input? (String)
  2. Validation: Do we need to verify the validity of the input IPv4 address? (Assumed not necessary as per the problem statement)
  3. Output: What should the output look like? (String with periods replaced by [.])
  4. Edge Cases: Are there any special edge cases to consider, such as an input string without any periods? (Handled implicitly by the string replace mechanism in C++)

Strategy

  1. Iterate through the string: We will iterate through each character of the input string to look for periods (.).
  2. Construct the output: As we move through the string, we will append each character to the output string. Whenever we encounter a period, we will append [.] to the output string instead of the period.
  3. Result: Return the constructed output string.

Code

Here’s the implementation in C++:

#include <iostream>
#include <string>

class Solution {
public:
    std::string defangIPaddr(std::string address) {
        std::string defangedAddress;
        for (char c : address) {
            if (c == '.') {
                defangedAddress += "[.]";
            } else {
                defangedAddress += c;
            }
        }
        return defangedAddress;
    }
};

int main() {
    Solution solution;
    std::string address = "1.1.1.1";
    std::string result = solution.defangIPaddr(address);
    std::cout << "Defanged IP Address: " << result << std::endl;
    return 0;
}

Time Complexity

This approach should work efficiently for the given problem constraints and typical input sizes.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI