This page looks best with JavaScript enabled

Leetcode - Defanging an IP Address (1108)

 ·  ☕ 1 min read  ·  🐺 Devoalda

Introduction

Given a valid (IPv4) IP address, return a defanged version of that IP address.

A defanged IP address replaces every period “.” with “[.]".

Input and Output

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"

Process

I’ve rarely done string replacement using Java, but upon looking around the internet
for some resources, I found the .replaceAll() method that replaces characters in a string.

Using this method, I was able to replace the .s in the given IP to [.]

Code

1
2
3
4
5
6
7
8
9
class Solution {
    public String defangIPaddr(String address) {
        address = address.replaceAll("\\.", "[.]");
        return address;

        // One liner
        // return address.replaceAll("\\.", "[.]");
    }
}

Afterthoughts

This is a simple challenge, I’ll probably try it with other languages in the near future

Share on

Devoalda
WRITTEN BY
Devoalda
Technophile