【Leetcode】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)

Java:

1. 征服代码:http://blog.csdn.net/linhuanmars/article/details/24683699

public class Solution {
  public ArrayList<String> restoreIpAddresses(String s) {  
        ArrayList<String> res = new ArrayList<String>();  
        if(s==null||s.length()==0) return res;
        help(s,0,1,"",res);
        return res;
    }  
    private void help(String s, int index, int segment, String item, ArrayList<String> res )
    {
        if(index>=s.length())
        {
            return;
        }
        if(segment==4)
        {
            String str=s.substring(index);
            if(isValid(str))
            {
                 res.add(item+"."+str);
            }
            return;
        }
        for(int i=1;i<4&&(i+index<=s.length());i++)
        {
            String str=s.substring(index,index+i);
            if(isValid(str))
            {
                if(segment==1)
                {
                    help(s,index+i,segment+1,str,res);
                }
                else
                {
                    help(s,index+i,segment+1,item+"."+str,res);
                }
            }            
        }    
    }
    private boolean isValid(String str)
    {
        if(str==null||str.length()>3) return false;
        int num=Integer.parseInt(str);
        if(str.charAt(0)=='0'&&str.length()>1) return false;
        
        return num>=0&&num<=255;
        
    }
}


2. 第二种解法 类似于对征服代码的解释,http://blog.csdn.net/u011095253/article/details/9158449

public class Solution {
    public ArrayList<String> restoreIpAddresses(String s) {
        ArrayList<String> res = new ArrayList<String>();
        if (s.length()<4||s.length()>12) return res;
        dfs(s,"",res,0);
        return res;
    }
    
    public void dfs(String s, String tmp, ArrayList<String> res, int count){
        if (count == 3 && isValid(s)) {
            res.add(tmp + s);
            return;
        }
        for(int i=1; i<4 && i<s.length(); i++){
            String substr = s.substring(0,i);
            if (isValid(substr)){
                dfs(s.substring(i), tmp + substr + '.', res, count+1);
            }
        }
    }
    
    public boolean isValid(String s){
        if (s.charAt(0)=='0') return s.equals("0");
        int num = Integer.parseInt(s);
        return num<=255 && num>0;
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值