LeetCode Challenge #5: Defanging an IP Address

LeetCode Challenge #5: 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 "[.]".

Example 1:

Input: address = "1.1.1.1"
Output: "1[.]1[.]1[.]1"

Step-by-Step Solution

Identify Patterns This question is very straightforward.

  1. The output is a String.
  2. This is a string manipulation problem. Use .replace().

Write the Pseudocode

  1. Replace every "." with "[.]" using the .replace() function.
  2. Return the modified String.

Let's get coding! Now, we can write the Java code as follows:

class Solution {
    public String defangIPaddr(String address) {
        return address.replace(".", "[.]");
    }
}

Conclusion

This problem is good for beginners to practice String manipulation. It is very easy to understand and straightforward so there's not much to explain. Of course, there are infinite ways to solve this problem. Using a StringBuilder or an array are possible alternatives too. Knowing the built-in functions of the language that allows to manipulate strings is very important for every programmer. Learning regex would be useful too. Keep practicing and it will become more easier and faster to manipulate any strings.

ย