devoalda.gitlab.io/content/en/posts/leetcode-DefangIP.md

1.3 KiB
Executable File

author authorEmoji title date description draft hideToc enableToc enableTocContent tocPosition tocLevels libraries tags series categories image
Devoalda 🐺 Leetcode - Defanging an IP Address (1108) 2023-02-12T08:00:54+08:00 Leetcode Problem 1108 false false true true inner
h1
h2
h3
mathjax
Java
Leetcode
Leetcode

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

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