其他分享
首页 > 其他分享> > 1108. Defanging an IP Address

1108. Defanging an IP Address

作者:互联网

1108. Defanging an IP Address

题目描述

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"

分析:

题目的目的就是将一个字符串里的字符.替换为[.]

方法1

  1. 创建一个空字符ans作为答案;
  2. 遍历address,如果字符是.,就在ans后追加[.],否则就追加该字符;
  3. 返回ans
class Solution {
    public String defangIPaddr(String address) {
        char[] chars = address.toCharArray();
        StringBuilder stringbuilder = new StringBuilder();
        for (char c : chars) {
            if (c == '.') {
                stringbuilder.append("[.]");
            } else {
                stringbuilder.append(c);
            }
        }
        
        return stringbuilder.toString();
    }
}

方法2

使用子串的方法,根据.的位置获取子字符串,并替换.[.],再使用字符串连接即可;

class Solution {
    public String defangIPaddr(String address) {
        for (int i = 0; i < address.length(); i++) {
            if (address.charAt(i) == '.') {
                address = address.substring(0, i) + "[.]" + address.substring(i + 1);
                i += 2;
            }
        }
        return address;
    }
}

标签:字符,Defanging,String,IP,address,ans,stringbuilder,字符串,1108
来源: https://www.cnblogs.com/zhuobo/p/11257113.html