题解 | #数字字符串转化成IP地址#

数字字符串转化成IP地址

https://www.nowcoder.com/practice/ce73540d47374dbe85b3125f57727e1e

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param s string字符串
     * @return string字符串ArrayList
     */
    private LinkedList<Integer> tempList = new LinkedList<>();
    private ArrayList<String> rst = new ArrayList<>();

    public ArrayList<String> restoreIpAddresses(String s) {
        if (s == null || s.length() == 0) {
            return rst;
        }
        buildIp(s, 0);
        return rst;
    }

    private void buildIp(String s, int index) {
        if (index == s.length() && tempList.size() == 4) {
            rst.add(convert(tempList));
        }
        // 边界条件
        if (tempList.size() >= 4 || index >= s.length()) {
            return;
        }
        // 一位数字情况
        tempList.add(s.charAt(index) - '0');
        buildIp(s, index + 1);
        tempList.removeLast();
        // 两位数字情况
        if (index + 1 < s.length() && s.charAt(index) != '0') {
            tempList.add(10 * (s.charAt(index) - '0') + s.charAt(index + 1) - '0');
            buildIp(s, index + 2);
            tempList.removeLast();
        }
        // 三位数字情况
        if (index + 2 < s.length() && s.charAt(index) != '0') {
            int value = 100 * (s.charAt(index) - '0') + 10 * (s.charAt(index + 1) - '0') +
                        (s.charAt(index + 2) - '0');
            if (value >= 100 && value <= 255) {
                tempList.add(value);
                buildIp(s, index + 3);
                tempList.removeLast();
            }
        }

    }

    private String convert(LinkedList<Integer> tempList) {
        StringBuilder sb = new StringBuilder();
        for (Integer value : tempList) {
            sb.append(value + ".");
        }
        return sb.substring(0, sb.length() - 1);
    }
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务