Algorithm


Problem Name: 1108. 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.

Code Examples

#1 Code Example with Java Programming

Code - Java Programming


class Solution {
  public String defangIPaddr(String address) {
    StringBuilder sb = new StringBuilder();
    for (char c : address.toCharArray()) {
      sb.append(c == '.' ? "[.]" : c);
    }
    return sb.toString();
  }
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
address = "1.1.1.1"

Output

x
+
cmd
"1[.]1[.]1[.]1"

#2 Code Example with Javascript Programming

Code - Javascript Programming


const defangIPaddr = function(address) {
  return address.split('.').join('[.]')
};
Copy The Code & Try With Live Editor

Input

x
+
cmd
address = "1.1.1.1"

Output

x
+
cmd
"1[.]1[.]1[.]1"

#3 Code Example with Python Programming

Code - Python Programming


class Solution:
    def defangIPaddr(self, address: str) -> str:
        return address.replace(".", "[.]")
Copy The Code & Try With Live Editor

Input

x
+
cmd
address = "255.100.50.0"

Output

x
+
cmd
"255[.]100[.]50[.]0"

#4 Code Example with C# Programming

Code - C# Programming


using System.Text;

namespace LeetCode
{
    public class _1108_DefangingAnIPAddress
    {
        public string DefangIPaddr(string address)
        {
            var sb = new StringBuilder();
            foreach (var ch in address)
            {
                if (ch == '.')
                    sb.Append("[.]");
                else
                    sb.Append(ch);
            }

            return sb.ToString();
        }
    }
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
address = "255.100.50.0"

Output

x
+
cmd
"255[.]100[.]50[.]0"
Advertisements

Demonstration


Previous
#1106 Leetcode Parsing A Boolean Expression Solution in C, C++, Java, JavaScript, Python, C# Leetcode
Next
#1109 Leetcode Corporate Flight Bookings Solution in C, C++, Java, JavaScript, Python, C# Leetcode