Defanging an IP Address LeetCode Solution - The Coding Shala
Home >> LeetCode >> Defanging an IP Address
Other Posts You May Like
In this post, we will learn how to solve LeetCode's Defanging an IP Address problem and will implement its solution in Java.
Defanging an IP Address Problem
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"
Defanging an IP Address Java Solution
Approach 1
We can use Java String's inbuilt method replace.
Java Program:
class Solution { public String defangIPaddr(String address) { return address.replace(".", "[.]"); } }
Approach 2
Using StringBuilder.
Avoid using String instead use StringBuilder. it is much faster than the String.
Java Program:
class Solution { public String defangIPaddr(String address) { StringBuilder str = new StringBuilder(); for(int i=0; i<address.length(); i++) { if(address.charAt(i) == '.') { str.append("[.]"); } else { str.append(address.charAt(i)); } } return str.toString(); } }
- LeetCode - Word Subsets
- LeetCode - Shifting Letters
- LeetCode - Valid Boomerang
- LeetCode - Valid Square
- LeetCode - Flipping an Image
Comments
Post a Comment