Defanging an IP Address LeetCode Solution - The Coding Shala

Home >> LeetCode >> Defanging an IP Address

 In this post, we will learn how to solve LeetCode's Defanging an IP Address problem and will implement its solution in Java.

Defanging an IP Address Problem

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"

Example 2:
Input: address = "255.100.50.0"
Output: "255[.]100[.]50[.]0"

Defanging an IP Address Java Solution

Approach 1

We can use Java String's inbuilt method replace.

Java Program: 

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

Approach 2

Using StringBuilder.

Avoid using String instead use StringBuilder. it is much faster than the String.

Java Program: 

class Solution {
    public String defangIPaddr(String address) {
        StringBuilder str = new StringBuilder();
        for(int i=0; i<address.length(); i++) {
            if(address.charAt(i) == '.') {
                str.append("[.]");
            } else {
                str.append(address.charAt(i));
            }
        }
        return str.toString();
    }
}


Other Posts You May Like
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.

Comments

Popular Posts from this Blog

Shell Script to find sum, product and average of given numbers - The Coding Shala

Single Number 3 LeetCode Solution - The Coding Shala

LeetCode - Number of Good Pairs Solution - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

Java Method Overloading - The Coding Shala