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)

 

解决:

使用递归,每次截取满足条件的一段,最后一段还作判断是不是满足。

 

public class Solution {
      ArrayList<String> lis = new ArrayList<String>();
    public ArrayList<String> restoreIpAddresses(String s) {
    	if (s.length()<25)
    		ipHelper(s,0,0);
        return lis;
    }
    public void ipHelper(String s,int pos,int num){
        int len = s.length();
        if (num==3){
            if (pos < len){
            	String las = s.substring(pos);
            	if (len - pos >1){
            		if (las.startsWith("0")) return;
            	}
            	
            	if (len - pos >3 || len - pos >1 && las.startsWith("0") || len - pos ==3 && Integer.parseInt(las)>255) return;
            	lis.add(s);
            }
            else
                return;
        }
        
        num++;
        if (len - pos >0){
            String t = s.substring(0,pos+1)+"."+s.substring(pos+1);
            ipHelper(t,pos+1+1,num);
            if ("0".equals(s.substring(pos,pos+1))) return;
            if (len -pos>1){
                t = s.substring(0,pos+2)+"."+s.substring(pos+2);
                ipHelper(t,pos+2+1,num);
            }
            if (len -pos>2){
                t = s.substring(pos,pos+3);
                if (Integer.parseInt(t)<256){
                    t = s.substring(0,pos+3)+"."+s.substring(pos+3);
                    ipHelper(t,pos+3+1,num);
                }
            }
        }
        
    }
}


 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值