# Defanging an IP Address Leetcode Solution

Difficulty Level Easy
algorithms coding Interview interviewprep LeetCode LeetCodeSolutions String StringBuffer

## Problem Statement

In this problem, we are given an IP Address. We just have to convert it into a Defanged IP Address i.e. in our output string, all the “.” are converted to “[.]”. ### Example

#1:

`address = "1.1.1.1"`
`"1[.]1[.]1[.]1"`

#2:

`address = "255.100.50.0"`
`"255[.]100[.]50[.]0"`

## Approach 1 (Using String Stream/Builder)

For this problem we can use simple string stream or builder class to modify the given string.
We can use a string builder (in case of java) and string stream (in case of C++) to convert given string to output string.
We will traverse the input string from left to right. If any character is ‘.’ then, we will append “[.]” in output string. Otherwise we will simply append the character in output string too.

Algorithm

• Create an empty string stream or builder.
• Run a for loop to traverse each character of given string.
• For each character in string. If character is ‘.” then append “[.]” to string builder. Else append the same character to string builder.
• Convert the stream/builder to string and return it.

### Implementation for Defanging an IP Address Leetcode Solution

#### C++ Program

```#include <iostream>
#include <sstream>
using namespace std;
{
std::stringstream ss;

ss<<"[.]";//replacing . with [.]
}else{
}
}
return ss.str();
}

int main()
{
}```
`1[.]1[.]1[.]1`

#### Java Program

```import java.util.*;
import java.lang.*;

class Solution
{
{
StringBuilder sb=new StringBuilder();
sb.append("[.]");
}else{
}
}
return sb.toString();
}

public static void main(String args[])
{
}
}```
`1[.]1[.]1[.]1`

### Complexity Analysis for Defanging an IP Address Leetcode Solution

#### Time Complexity

O(n) : we are traversing the given string linearly, Thus it’s O(n).

K-th Distinct Element in an Array

#### Space Complexity

O(n) : In case of java we have used string builder which is linear extra space and in case of C++ we have used string stream thus space complexity is O(n).

## Approach 2 (Using In-built Function)

We will use regex replace function in C++ and replace all function in java:

We can use regex_replace function of C++ to replace all “.” to “[.]”.
Also, in case of java, we can use replaceAll() function to replace all “.” to “[.]”.

### Implementation for Defanging an IP Address Leetcode Solution

#### C++ Program

```#include <iostream>
#include <regex>
using namespace std;
{
//. is covered by [] from both sides because . itself works as pipe and will give wrong result if not used like [.]
}

int main()
{
}```
`1[.]1[.]1[.]1`

#### Java Program

```import java.util.*;
import java.lang.*;

class Solution
{
{
/*
A period (.) has a special meaning there as does a pipe (|) as does a curly brace (}).
You need to escape them all using // before '.'.
*/
}

public static void main(String args[])
{
`1[.]1[.]1[.]1`