LeetCode 93. Restore IP Addresses

问题描述

  • Given a string containing only digits, restore it by returning all possible valid IP address combinations.
  • Example:
    Input: “25525511135”
    Output: [“255.255.11.135”, “255.255.111.35”]

问题分析

  • DFS + 回溯

代码实现

class Solution {
    public List<String> restoreIpAddresses(String s) {
        if (s == null) {
            return new ArrayList<String>();
        }
        char[] chs = s.toCharArray();
        StringBuilder ip = new StringBuilder();
        ArrayList<String> res = new ArrayList<>();
        findIp(chs, ip, 0, 0, res);
        return res;
    }

    //在chs[0 ~ i - 1]中已经得到了 sectionNum 个section,看剩下[i ~ length - 1]还能否一共加出4个section,若加出,则添加进res
    public void findIp(char[] chs, StringBuilder ip, int i, int sectionNum, ArrayList<String> res) {
        //注意递归终止条件,当该串用尽或者已经得到了4个section便停止
        if (i == chs.length || sectionNum == 4) {
            //只有该串恰好全部用来组成了4个section,才添加进结果集
            if (sectionNum == 4 && i == chs.length) {
                res.add(ip.toString());
            }
            return;
        }
        int length = ip.length();
        for(int k = i; k < chs.length && k < i + 3; k++) {
            //取str[i ~ i], str[i ~ i + 1] 和 str [i ~ i + 2],并保证不越界。
            String str = new String(chs, i, k - i + 1);
            if (isValid(str)) {
                //最后一部分不加"."
                ip = sectionNum == 3 ? ip.append(str) : ip.append(str).append(".");
                //继续dfs
                findIp(chs, ip, k + 1, sectionNum + 1, res);
                //回溯
                ip.setLength(length);
            }
        }
        return;
    }

    //检查是否是合法ip字段
    public boolean isValid(String str) {
        if (str.length() > 1 && str.charAt(0) - '0' == 0) {
            return false;
        }
        return Integer.valueOf(str) <= 255;
    }
}

猜你喜欢

转载自blog.csdn.net/zjxxyz123/article/details/80086534