Restore IP Addresses

来源:互联网 发布:java游戏下载 编辑:程序博客网 时间:2024/05/21 07:04

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 {

    public List<String> restoreIpAddresses(String s) {
        List<String> res = new ArrayList<String>();
        if(null == s || s.length() < 4 || s.length() > 12){
            return res;
        }
        dfs(res,s,0,1,"");
        return res;
    }
    public void dfs(List<String> res,String s,int start,int pos,String tem){
        if((start > (s.length() -1)) && (pos < 4)){
            return;
        }
        if(pos == 4){
            if(isvalid(s.substring(start))){
                tem = tem + "." + s.substring(start);
                res.add(tem);
                return;
            }
        }
        for(int i = 1;i <= 3;i++){
            if((start + i) >= s.length()){
                return;
            }
            if(isvalid(s.substring(start,start + i))){
                if(pos != 1){
                    tem = tem + "." + s.substring(start,start + i);
                    dfs(res,s,start + i,pos + 1,tem);
                    tem = tem.substring(0,tem.length()-i-1);
                }else{
                    tem = tem + s.substring(start,start + i);
                    dfs(res,s,start + i,pos + 1,tem);
                    tem = "";
                }
            }
            
            
        }
    }
    public boolean isvalid(String num){
        if(null == num || num.length() <= 0 ){
            return false;
        }
        Long a = Long.parseLong(num);
        if(num.length()==1 && a>=0 && a<=9) return true;
        if(num.length()==2 && !num.startsWith("0") && a>=10 && a<=99) return true;
        if(num.length()==3 && !num.startsWith("0") && a>=100 && a<=255) return true;
        return false;
    }
}
0 0
原创粉丝点击