合法ip序列

Given a string containing only digits, restore it by returning all possible valid IP address combinations.

For example:
Given "25525511135",

return ["255.255.11.135", "255.255.111.35"]. (Order does not matter)


用pos[]放第i个点打的位置。然后搜索,当前节点合法,扩展节点的时候以当前的点的位置为基准,向右一位一位的增加,最多不超过3。

判断合法性要考虑每一节位数》1首位不能为0.


使用hashset判重。

boolean isValid(String s) {
        if (s == null || s.length() == 0 || s.length() > 3)
            return false;
        if (s.length() > 1 && s.charAt(0) == '0')
            return false;
        Integer i = Integer.valueOf(s);
        if (i >= 0 && i <= 255) return true;
        return false;
    }


     void search(String s, int pos[], int cur, int n, int cnt) {
        if (cur == n || cnt > 3) {
            String ip1 = s.substring(0, pos[1] + 1)
                    .concat(".");
            String ip2 = s.substring(pos[1] + 1, pos[2] + 1).concat(".");

            String ip3 = s.substring(pos[2] + 1, pos[3] + 1).concat(".");

            String ip4 = s.substring(pos[3] + 1);

            if (isValid(ip4))
                ips.add(ip1.concat(ip2).concat(ip3).concat(ip4));

            return;
        }
        for (int i = 1; i <= 3; i++) {
            if (cur + i >= n)
                continue;
            String str = s.substring(cur + 1, cur + i + 1);
            if (isValid(str)) {
                pos[cnt] = cur;
                search(s, pos, cur + i, n, cnt + 1);

            }
        }
    }

     Set<String> ips = new HashSet<String>();

    public List<String> restoreIpAddresses(String s) {
        if (s == null || s.length() == 0 || s.length() > 12 || s.length() < 4)
            return new ArrayList<String>();

        int pos[] = new int[4];
        search(s, pos, -1, s.length(), 0);
        return new ArrayList<String>(ips);

    }


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值