lintcode(426)恢复IP地址

描述 :

给一个由数字组成的字符串。求出其可能恢复为的所有IP地址。

样例;

给出字符串 "25525511135",所有可能的IP地址为:

[
  "255.255.11.135",
  "255.255.111.35"
]

(顺序无关紧要)


思路:

两个计数指针,一个计数执行到字符串的第几位,一个计数执行到IP的第几位,要判断value<256并且首位不能为0

public class Solution {
    /**
     * @param s the IP string
     * @return All possible valid IP addresses
     */
    public ArrayList<String> restoreIpAddresses(String s) {
        // Write your code here
        ArrayList<String> result = new ArrayList<String>();
        String temp = new String();
        search(s , temp , result , 4 , 0 , s.length());
        return result;
    }

    public void search(String s , String temp , ArrayList<String> result , int count , int index , int len){
        //index 操作到字符串第几个字符
        //count 操作到IP第几位
        if(count == 0 && index == len){
            result.add(temp);
            return ;
        }
        if((count == 0 && index < len) || (count > 0  && index == len)){
            return ;
        }
        
        int value = 0;
        boolean flag = true;//第一个字符是否为0标志
        while(index < len && flag){
            if(value == 0 && s.charAt(index) == '0'){
                flag = false;
            }
            value = value * 10 + s.charAt(index) - '0';
            index++;
            if(value < 256){
                String record = "";
                if(count == 1){
                    record = temp + Integer.toString(value);
                }else{
                    record = temp + Integer.toString(value) + '.';
                }
                
                search(s , record , result , count - 1 , index , len);
            }
        }
    }
}



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值