LeetCode第93题--复原IP地址

给定一个只包含数字的字符串,复原它并返回所有可能的 IP 地址格式。

示例:
输入: “25525511135”
输出: [“255.255.11.135”, “255.255.111.35”]

class Solution {
private:
    bool isValidIp(string &strTemp)
    {
        if(strTemp.length() == 0 || (strTemp.length() > 1 && strTemp[0] == '0')) return false;		//注意IP没有“01”这种的
        int num = atoi(strTemp.c_str());
        return (num >= 0 && num <= 255);
    }
    
    void dfs(vector<string> &vecRes, string &s, string strTemp, int left, int depth)
    {        
        for(int right = left; right < s.length() && right <= left+2; right++)		//注意此处的循环条件right <= left+2
        {
            if(s.length()-right-1 > (4-depth)*3) continue;		//注意此处是s.length()-right-1,表示是该字符后面的字符
            if(s.length()-right-1 < 4-depth) continue;
            
            string strRes(s, left, right-left+1);			//初始化截取字符串
            if(isValidIp(strRes))
            {
                if(depth == 4)
                {
                    strTemp += strRes;
                    vecRes.push_back(strTemp);
                    return;
                }
                dfs(vecRes, s, strTemp+strRes+'.', right+1, depth+1);
            }
        }
        
    }
    
public:
    vector<string> restoreIpAddresses(string s) {
        vector<string> vecRes;
        if(s.length() > 12) return vecRes;
        dfs(vecRes, s, "", 0, 1);		//此处递归的深度从1开始
        return vecRes;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值