Back to photostream

Defanging an IP Address Leetcode Solution

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"

"1111"

#2:

address = "255.100.50.0"

"255100500"

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

#include

using namespace std;

string defangIPaddr(string address)

{

std::stringstream ss;

 

for(int i=0;i

 

www.tutorialcup.com/leetcode-solutions/defanging-an-ip-ad...

26 views
0 faves
0 comments
Uploaded on September 3, 2021
Taken on January 21, 2021