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

Restore IP Addresses

时间:2014-08-17 22:48:32      阅读:217      评论:0      收藏:0      [点我收藏+]

标签:算法   dfs   

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 LinkedList<String>();
        if(s==null || s.length()<=3) return res;
        dfs(0,0,new String(""),s,res);
        return res;
    }
    public void dfs(int start,int points,String IPstr,String s,List<String> res){
        if(start==s.length()&& points==4){
            IPstr=IPstr.substring(0,IPstr.length()-1);
            res.add(IPstr);
            return;
        }
        if(points>=4) return;
        if(s.length()-start<4-points) return;
        if(s.length()-start>(4-points)*3) return;
        if(start+1<=s.length()){
            String sub1=s.substring(start,start+1);
            dfs(start+1,points+1,IPstr+sub1+".",s,res);
        }
        if(start+2<=s.length()){
            String sub2=s.substring(start,start+2);
            if(sub2.compareTo("10")>=0 && sub2.compareTo("99")<=0){
                dfs(start+2,points+1,IPstr+sub2+".",s,res);
            }
        }
        if(start+3<=s.length()){
            String sub3=s.substring(start,start+3);
            if(sub3.compareTo("100")>=0 && sub3.compareTo("255")<=0){
                dfs(start+3,points+1,IPstr+sub3+".",s,res);
            }
        }
    }
}

Restore IP Addresses,布布扣,bubuko.com

Restore IP Addresses

标签:算法   dfs   

原文地址:http://blog.csdn.net/dutsoft/article/details/38645339

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