其他分享
首页 > 其他分享> > 93. 复原 IP 地址

93. 复原 IP 地址

作者:互联网

✅做题思路or感想

这种字符串切割的问题都可以用回溯法来解决

递归三部曲:

class Solution {
public:
    vector<string>result;
    vector<string>temp;
    bool isGood(string s, int startIndex, int i) {
        //子串长度限制
        if (i - startIndex + 1 >= 4)return false;
        string str = s.substr(startIndex, i - startIndex + 1);
        //由子串转化成的数字的范围的限制
        if (0 > stoi(str) || stoi(str) > 255)return false;
        //前导0的限制
        if (str.size() > 1 && str[0] == '0')return false;
        //非法字符的限制
        for (int j = 0; j < str.size(); j++) {
            if (str[j] >= '0' && str[j] <= '9')continue;
            else return false;
        }
        return true;
    }
    void dfs(string s, int startIndex) {
        //递归中止条件
        if (temp.size() == 4 && startIndex >= s.size()) {
            string str;
            //需要把子串拿出来做一点加工后再放到result中!!!
            for (int i = 0; i < temp.size(); i++) {
                if (i != temp.size() - 1) {
                    str = str + temp[i] + ".";
                } else {
                    str = str + temp[i];
                }
            }
            result.push_back(str);
            return;
        }
        for (int i = startIndex; i < s.size(); i++) {
            if (isGood(s, startIndex, i)) {
                string str = s.substr(startIndex, i - startIndex + 1);
                temp.push_back(str);
                dfs(s, i + 1);
                temp.pop_back();	//回溯
            } 
        }
    }
    vector<string> restoreIpAddresses(string s) {
        dfs(s, 0);
        return result;
    }
};

标签:子串,return,temp,IP,startIndex,str,93,复原,size
来源: https://www.cnblogs.com/doomaa/p/16093589.html