71 lines
1.3 KiB
Markdown
71 lines
1.3 KiB
Markdown
---
|
|
author: "Devoalda"
|
|
authorEmoji: 🐺
|
|
title: "Leetcode - Defanging an IP Address (1108)"
|
|
date: 2023-02-12T08:00:54+08:00
|
|
description: Leetcode Problem 1108
|
|
draft: false
|
|
hideToc: false
|
|
enableToc: true
|
|
enableTocContent: true
|
|
tocPosition: inner
|
|
tocLevels: ["h1", "h2", "h3"]
|
|
libraries:
|
|
- mathjax
|
|
tags:
|
|
- Java
|
|
- Leetcode
|
|
series:
|
|
- Leetcode
|
|
categories:
|
|
-
|
|
image:
|
|
---
|
|
|
|
# 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
|
|
|
|
```java
|
|
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
|