码迷,mamicode.com
首页 > 其他好文 > 详细

Jan 24 - Restore Ip Addresses; BackTracking; Recursion; DFS;

时间:2016-01-25 08:44:45      阅读:138      评论:0      收藏:0      [点我收藏+]

标签:

 

Code:

public class Solution {
    public List<String> restoreIpAddresses(String s) {
        List<String> list = new ArrayList<>();
        int len = s.length();
        if(len < 4) return list;
        String ip = "";
        validIpAddresses(s, ip, 4, len, 0, list);
        return list;
    }
    
    public void validIpAddresses(String s, String ip, int n, int len, int pos, List<String> list){
        int size = len - pos;
        if(size <= 0) return;
        if(n == 1){
            if(size > 3) return;
            String block = s.substring(pos, pos+size);
            if(Integer.parseInt(block) > 255) return;
            if(size > 1 && s.charAt(pos) == ‘0‘) return;
            ip = ip + block;
            list.add(ip);
            return;
        }
        if(size > 3) size = 3;
        for(int i = 1; i <= size; i++){
            String block = s.substring(pos, pos+i);
            if(i > 1 && s.charAt(pos) == ‘0‘) return;
            if(Integer.parseInt(block) > 255) return;
            validIpAddresses(s, ip + block +".", n-1, len, pos+i, list);
        }
    }
}

 

Jan 24 - Restore Ip Addresses; BackTracking; Recursion; DFS;

标签:

原文地址:http://www.cnblogs.com/5683yue/p/5156505.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!