Skip to content

93.复原IP地址

题目链接:leetcode 复原IP地址

题目

有效 IP 地址 正好由四个整数(每个整数位于 0 到 255 之间组成,且不能含有前导 0),整数之间用 '.' 分隔。

例如:"0.1.2.201" 和 "192.168.1.1" 是 有效 IP 地址,但是 "0.011.255.245"、"192.168.1.312" 和 "192.168@1.1" 是 无效 IP 地址。

给定一个只包含数字的字符串 s ,用以表示一个 IP 地址,返回所有可能的有效 IP 地址,这些地址可以通过在 s 中插入 '.' 来形成。你 不能 重新排序或删除 s 中的任何数字。你可以按 任何 顺序返回答案。

示例 1:

输入:s = "25525511135" 输出:["255.255.11.135","255.255.111.35"]

示例 2:

输入:s = "0000" 输出:["0.0.0.0"]

示例 3:

输入:s = "101023" 输出:["1.0.10.23","1.0.102.3","10.1.0.23","10.10.2.3","101.0.2.3"]

精选答案

java
class Solution {
   public List<String> restoreIpAddresses(String s) {
        int len = s.length();
        //存结果的过程,比如,[111,22,]
        Deque<String> path = new LinkedList<>();
        List<String> res = new ArrayList<>();
        if (len < 4 || len > 12) {
            return res;
        }
        dfs(s, len, 0, 0, path, res);
        return res;
    }

    private void dfs(String s, int len, int start, int selectedCount, Deque<String> path, List<String> res) {
        //找到符合条件的结果,退出本层搜索,或者搜完了所有字符
        if (start == len && selectedCount == 4) {
            res.add(String.join(".", path));
            return;
        }

        //剪枝 已经不需要再往后搜索了(不剪枝也不会报错,只是效率会低一些)
        //剩下的字符<最少需要的字符数 或者>剩下最多能承载的字符数
        //比如1:2552551->255.255.1后面没有字符可以选了
        //比如2:2552551->2.5.5.2551 后面多了个字符1
        if (len - start < 4 - selectedCount || len - start > 3 * (4 - selectedCount)) {
            return;
        }

        //向下遍历最多3个字符,得到1~3种情况的分枝
        for (int i = 0; i < 3; i++) {
            if (start + i >= len) {
                break;
            }
            //判断是否符合0~255之间
            String ipSegment = judgeRule(s, start, start + i);
            if ("false".equals(ipSegment)) {
                continue;
            }
            path.addLast(ipSegment);
            //递归往下
            dfs(s, len, start + i + 1, selectedCount + 1, path, res);
            path.removeLast();
        }

    }

    private String judgeRule(String s, int start, int i) {
        //过滤以0开头的数字
        if (i - start + 1 > 1 && s.charAt(start) == '0') {
            return "false";
        }
        //substring左开右闭
        String substring = s.substring(start, i + 1);
        if (Integer.parseInt(substring) > 255) {
            return "false";
        }
        return substring;
    }
}