1108. Defanging an IP Address(Solution || Leetcode easy || Java)

Palakkgoyal
1 min readNov 22, 2022

--

Runtime: 0 ms, faster than 100.00% of Java online submissions for Defanging an IP Address.

Memory Usage: 39.8 MB, less than 98.90% of Java online submissions for Defanging an IP Address.

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"

Constraints:

  • The given address is a valid IPv4 address.

SOLUTION:

class Solution {
public String defangIPaddr(String address) {
//We will create stringbuilder to occupy less space while modifying
//the string
StringBuilder temp = new StringBuilder(address);

int i = 0;

while(i < temp.length()){
if(temp.charAt(i) == '.'){
temp.replace(i,i+1,"[.]");
i += 3;
}else{
i++;
}
}

return temp.toString();
}
}

Thank you for reading. If you have any queries then, please let me know in the comment section. I will surely be responsive toward it.

--

--

Palakkgoyal
Palakkgoyal

Written by Palakkgoyal

Solutions to all your coding related problems at one point. DSA question on daily basis and much more.

No responses yet