LeetCode 93. 复原 IP 地址

有效 IP 地址 正好由四个整数(每个整数位于 0 到 255 之间组成,且不能含有前导 0),整数之间用 '.' 分隔。

  • 例如:"0.1.2.201" 和 "192.168.1.1" 是 有效 IP 地址,但是 "0.011.255.245""192.168.1.312" 和 "[email protected]" 是 无效 IP 地址。

给定一个只包含数字的字符串 s ,用以表示一个 IP 地址,返回所有可能的有效 IP 地址,这些地址可以通过在 s 中插入 '.' 来形成。你 不能 重新排序或删除 s 中的任何数字。你可以按 任何 顺序返回答案。

示例 1:

输入:s = "25525511135"
输出:["255.255.11.135","255.255.111.35"]

示例 2:

输入:s = "0000"
输出:["0.0.0.0"]

示例 3:

输入:s = "101023"
输出:["1.0.10.23","1.0.102.3","10.1.0.23","10.10.2.3","101.0.2.3"]

提示:

  • 1 <= s.length <= 20
  • s 仅由数字组成
/**
 *
 * @param s
 * @param startIndex 搜索的起始位置
 * @param pointNum 添加逗点的数量
 */
bool isValid(string &s, int start, int end) {
    if (start > end) return false;
    //开头是0不合法
    if (s[start] == '0' && start != end) {
        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) return false;
    }
    return true;
}

vector result;

void backtracking(string &s, int startIndex, int pointNum) {
    if (pointNum == 3) {
        //判断字符是否有效果有效则加入结果集
        if (isValid(s, startIndex, s.size() - 1)) {
            result.push_back(s);;
        }
        return;
    }
    //单层递归逻辑
    for (int i = startIndex; i < s.size(); ++i) {
        //截取当前切割的字符判断是否合法
        if (isValid(s, startIndex, i)) {
            //加入.  btw: c++语法中insert要+1
            s.insert(s.begin() + i + 1, '.');
            pointNum++;
            //递归 注意这里是从i+2开始,因为插入了逗点
            backtracking(s, i + 2, pointNum);
            //回溯
            pointNum--;
            s.erase(s.begin() + i + 1);
        } else {
            break;// 不合法,直接结束本层循环
        }
    }
}

vector restoreIpAddresses(string s) {
    backtracking(s, 0, 0);
    return result;
}

你可能感兴趣的:(leetcode,tcp/ip,算法)