LeetCode 93. Restore IP Addresses(恢复IP地址)

21 篇文章 0 订阅
20 篇文章 0 订阅

原题网址:https://leetcode.com/problems/restore-ip-addresses/

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)

方法:深度优先搜索。

public class Solution {
    /*
"0000"
"00000"
"25525511135"
"9245587303"
"0279245587303"
"010010"
    */
    private void find(String s, int[] pos, int step, List<String> addresses) {
        if (step == pos.length-1) {
            if (pos[step]-pos[step-1]>3) return;
            if (pos[step]-pos[step-1]>1 && s.charAt(pos[step-1]) == '0') return;
            int a = Integer.parseInt(s.substring(pos[step-1]), 10);
            if (a>255) return;
            StringBuilder sb = new StringBuilder();
            for(int i=0; i<pos.length-1; i++) {
                if (i>0) sb.append(".");
                sb.append(s.substring(pos[i], pos[i+1]));
            }
            addresses.add(sb.toString());
            return;
        }
        // Set<Integer> used = new HashSet<>();
        for(int i=pos[step-1]+1; i+(3-step)<pos[pos.length-1]; i++) {
            int a = Integer.parseInt(s.substring(pos[step-1], i), 10);
            if (a>255) break;
            // if (used.contains(a)) continue;
            // used.add(a);
            pos[step] = i;
            find(s, pos, step+1, addresses);
            if (a==0) break;
        }
    }
    public List<String> restoreIpAddresses(String s) {
        List<String> addresses = new ArrayList<>();
        int[] pos = new int[5];
        pos[0] = 0;
        pos[4] = s.length();
        find(s, pos, 1, addresses);
        return addresses;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值