leetcode-master/problems/0093.复原IP地址.md

2.2 KiB
Raw Blame History

题目地址

https://leetcode-cn.com/problems/restore-ip-addresses/

思路

C++代码

class Solution {
private:
    vector<string> result;// 记录结果
    // startIndex: 搜索的起始位置pointNum:添加逗点的数量
    void search(string& s, int startIndex, int pointNum) {
        if (pointNum == 3) { // 逗点数量为3时分隔结束
            // 判断第四段子字符串是否合法如果合法就放进result中
            if (isValid(s, startIndex, s.size() - 1)) {
                result.push_back(s);
            }
            return;
        }
        // 从起始位置开始构造字段字符串串
        for (int i = startIndex; i < s.size(); i++) {
            // 判断 [startIndex,i] 这个区间的子串是否合法
            if (isValid(s, startIndex, i)) {
                // 合法在i的后面插入一个逗点
                s.insert(s.begin() + i + 1 , '.');
                // 插入逗点之后下一个子串的起始位置为i+2
                search(s, i + 2, pointNum + 1);
                s.erase(s.begin() + i + 1); // 回溯时删掉逗点
            } else break;
        }
    }
    // 判断字符串s在左闭又闭区间[start, end]所组成的数字是否合法
    bool isValid(const string& s, int start, int end) {
        if (start > end) {
            return false;
        }
        if (s[start] == '0' && start != end) {// 0开头的数字不合法
                return false;
        }
        int num = 0;
        for (int i = start; i <= end; i++) {
            if (s[i] > '9' || s[i] < '0') { // 遇到非数字字符不合法
                return false;
            }
            num = num * 10 + (s[i] - '0');
            if (num > 255) { // 如果大于255了不合法
                return false;
            }
        }
        return true;
    }
public:
    vector<string> restoreIpAddresses(string s) {
        result.clear();
        search(s, 0, 0);
        return result;
    }
};

更多算法干货文章持续更新可以微信搜索「代码随想录」第一时间围观关注后回复「Java」「C++」 「python」「简历模板」「数据结构与算法」等等就可以获得我多年整理的学习资料。