93.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)
思路
基本思路就是取出一个合法的数字,作为IP地址的一项,然后递归处理剩下的项。可以想象出一颗树,每个结点有三个可能的分支(因为范围是0-255,所以可以由一位两位或者三位组成),每个数都必须小于等于255。并且这里树的层数不会超过四层,因为IP地址由四段组成,到了之后我们就没必要再递归下去,可以结束了。

class Solution {
public:
    vector<string> restoreIpAddresses(string s) {
        vector <string> res;
        int size = s.size();
        if(size == 0){
            return res;
        }
        string ip;
        helper(s,1,0,ip,res);
        return res;
    }
    void helper(string &s,int step, int idx, string ip, vector<string>&res){
        int size = s.size();
        if(step == 5){
            if(idx == size){
                res.push_back(ip);
            }
            return;
        }
        string ipCur;
        for(int i =1;i<=3;++i){
            //不能以0开始(单个0可以)
            if(i != 1 && s[idx] == '0'){
                break;
            }
            if(idx+i<=size){
                ipCur = s.substr(idx,i);
                if(to_int(ipCur)<=255){
                    string tmp = ip;  //定义一个局部变量记录之前的状态
                    if(step != 1){
                        tmp +='.';
                    }
                    tmp += ipCur;
                    helper(s, step+1,idx+i,tmp,res);
                }
            }
        }
        
    }
    int to_int(string str){
        int size = str.size();
        if(size == 0){
            return 0;
        }
        int result = 0;
        for(int i = 0;i < size;++i){
            result = result * 10 + str[i] - '0';
        }
        return result;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值