93. Restore IP Addresses

class Solution {
    public List<String> restoreIpAddresses(String s) {
        List<String> res=new ArrayList<String>();
        restoreIpAddresses("", 0, 0, s, res);
        return res;
    }
    private void restoreIpAddresses(String ip, int idx, int blocks, String s, List<String> res){
        if(blocks==4&&idx==s.length())
        {
            res.add(ip);
            return;
        }
        if(blocks>4||idx==s.length())
            return;
        if(blocks>0)
            ip+=".";
        if(idx<s.length()&&s.charAt(idx)>='0'&&s.charAt(idx)<='9')
            restoreIpAddresses(ip+s.charAt(idx), idx+1, blocks+1, s, res);
        if(idx+1<s.length())
        {
            int num=Integer.parseInt(s.substring(idx,idx+2));
            if(9<num&&num<100)
                restoreIpAddresses(ip+s.substring(idx,idx+2), idx+2, blocks+1, s, res);
        }
        if(idx+2<s.length())
        {
            int num=Integer.parseInt(s.substring(idx,idx+3));
            if(99<num&&num<256)
                restoreIpAddresses(ip+s.substring(idx,idx+3), idx+3, blocks+1, s, res);
        }
    }
}

 

posted @ 2017-09-29 01:52  Weiyu Wang  阅读(172)  评论(0编辑  收藏  举报