码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 1108. Defanging an IP Address

时间:2019-12-22 11:02:53      阅读:71      评论:0      收藏:0      [点我收藏+]

标签:stringbu   space   ++   ddr   builder   public   ons   ret   else   

原题链接在这里: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

标签:stringbu   space   ++   ddr   builder   public   ons   ret   else   

原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/12078982.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!