Restore IP Addresses

在这里插入图片描述
解析:一般求解组合或排列,都是递归的思想
1.将IP地址分为4端来看待,每一段的位数至少为1,且不能大于3
2.依次将每一段的位数递增1-3,检测是否符合IP地址的要求,即每一段要<=255
特殊情况的处理:
1.等于0,位数不能超过1,即出现连续的’0’就不满足要求
2.'0’开头,则位数不能大于1

class Solution {
public:
    vector<string> restoreIpAddresses(string s) {
        vector<string> res;
        if (s.length() <= 3 || s.length() > 12) return res; //不符合IP地址
        vector<int> res_cnt;
        DFS(s, res, res_cnt, 1, s.length());
        return res;
    }
    void DFS(string& s, vector<string>& res, vector<int> res_cnt, int pos, int re){
        if (!res_cnt.empty() && res_cnt.back() > 3) return;
        if (res_cnt.size() == 3 && re > 0 && re <= 3){
            int i = 0;
            string str_res = "";
            string temp;
            for (int j = 0; j < res_cnt.size(); ++j){
                temp = s.substr(i, res_cnt[j]);
                if (isValid(temp) == false) return; //验证每一段的有效性
                str_res += temp + ".";
                i += res_cnt[j];
            }
            temp = s.substr(i, re);
            if (isValid(temp) == false) return;
            str_res += temp;
            res.push_back(str_res);
        }
        for (int i = pos; i <= re; ++i){
            re -= i;
            res_cnt.push_back(i);
            //注意,这里是pos,不能是i,如果是i,每一端的位数都会递增,高端位的短地址检测不到
            DFS(s, res, res_cnt, pos, re); 
            res_cnt.pop_back();
            re += i;
        }
    }
    bool isValid(string s){
        if (s.empty() || (s[0] == '0' && s.length() > 1)) return false;
        int num = atoi(s.c_str());
        return num >= 0 && num <= 255;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值