Skip to main content

Command Palette

Search for a command to run...

LeetCode Challenge #5: Defanging an IP Address

Published
View as Markdown
LeetCode Challenge #5: Defanging an IP Address
V

I'm a solutions engineer lead, GitHub Star, Director of WomenDevsSG, and co founder of ragTech. I work at the intersection of tech, systems, and leadership, and this blog is where I share my journey through all three. Expect honest reflections, real experiences, and thoughts that are still forming rather than polished career advice.

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.