LeetCode 1108. Defanging an IP Address

Posted Dylan_Java_NYC

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 1108. Defanging an IP Address相关的知识,希望对你有一定的参考价值。

原题链接在这里:https://leetcode.com/problems/defanging-an-ip-address/

题目:

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

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.

题解:

Replace all "." with "[.]".

Time Complexity: O(n). n = address.length().

Space: O(n).

AC Java:

 1 class Solution {
 2     public String defangIPaddr(String address) {
 3         if(address == null || address.length() == 0){
 4              return address;
 5         }
 6         
 7         StringBuilder sb = new StringBuilder();
 8         for(int i = 0; i<address.length(); i++){
 9             char c = address.charAt(i);
10             if(c == ‘.‘){
11                 sb.append("[.]");
12             }else{
13                 sb.append(c);
14             }
15         }
16         
17         return sb.toString();
18     }
19 }

 

以上是关于LeetCode 1108. Defanging an IP Address的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode.1108-使IP地址无效(Defanging an IP Address)

leetcode1108

每日编程-440期Leetcode1108.IP 地址无效化

LeetCode 1108 IP地址无效化[暴力] HERODING的LeetCode之路

Python描述 LeetCode 1108. IP 地址无效化

Python描述 LeetCode 1108. IP 地址无效化