复原IP地址(LeetCode93)

题目描述

给定一个只包含数字的字符串,复原它并返回所有可能的 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 = "25525511135"
输出:["255.255.11.135","255.255.111.35"]

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

输入:s = "1111"
输出:["1.1.1.1"]`

输入:s = "010010"
输出:["0.10.0.10","0.100.1.0"]``

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

题解和思路

这是一道很明显的深度优先搜索的题目。因为IPv4是4个十进制位数组成,所以我们可以定义一个数组,用来存放dfs过程中复合要求的ip地址,并且这个数组的长度只有四段,我们在dfs的过程中维护两个状态,一个是字符串索引状态,一个是每段ip的索引状态。还有一个比较难想的就是需要把符合条件的字符转换为ip地址,这里用到了*10进位的方法。详细看代码注释。

List<String> res;
    int[] segment = new int[4];

    public List<String> restoreIpAddresses(String s) {
        res = new ArrayList<>();
        dfs(s, 0, 0);
        return res;
    }

    /**
     * @param s
     * @param id    ip段索引
     * @param index 字符串索引
     */
    private void dfs(String s, int id, int index) {
        if (id == 4) {
            if (index == s.length()) {
                StringBuilder ss = new StringBuilder();
                for (int i = 0; i < 4; i++) {
                    if (i != 3) {
                        ss.append(segment[i] + ".");
                    } else {
                        ss.append(segment[i]);
                    }
                }
                res.add(ss.toString());
            }
            // 这里必须返回。
            return;
        }
        //  特殊判断  搜索到了最后
        if (index == s.length()) return;
        // 不能有0前导,所以这个数单独就能作为一个IP段
        if (s.charAt(index) == '0') {
            segment[id] = 0;
            dfs(s, id + 1, index + 1);
        }
        // 枚举可能符合要求的ip段进行dfs
        int ip = 0;
        for (int end = index; end < s.length(); end++) {
            ip = 10 * ip + s.charAt(end) - '0';
            if (ip > 0 && ip <= 255) {
                segment[id] = ip;
                dfs(s, id + 1, end + 1);
            } else {
                // 提前返回 剪枝
                break;
            }
        }
        return;
    }

    public static void main(String[] args) {
        Solution_93_2 ss = new Solution_93_2();
        List<String> list = ss.restoreIpAddresses("101023");
        for (String tmp : list) {
            System.out.println(tmp);
        }
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值