当前位置 : 首页 > 保养数据

基于回溯算法的IP地址复原与验证

<|begin▁of▁sentence|># 1. 题目 #### [93. 复原 IP 地址](https://leetcode-cn.com/problems/restore-ip-addresses/) 难度中等851 **有效 IP 地址** 正好由四个整数(每个整数位于 `0` 到 `255` 之间组成,且不能含有前导 `0`),整数之间用 `'.'` 分隔。 - 例如:`"0.1.2.201"` 和`"192.168.1.1"` 是 **有效** IP 地址,但是 `"0.011.255.245"`、`"192.168.1.312"` 和 `"192.168@1.1"` 是 **无效** 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` 仅由数字组成 # 2. 题解 # 3. code ```c++ class Solution { public: vector ans; string path; bool isValid(const string& s, int start, int end) { if (start > end) return false; 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; } void backtracking(string s, int startIdx, int pointNum) { if (pointNum == 3) { if (isValid(s, startIdx, s.size() - 1)) { ans.push_back(s); } return; } for (int i = startIdx; i < s.size(); i++) { if (isValid(s, startIdx, i)) { s.insert(s.begin() + i + 1, '.'); pointNum++; backtracking(s, i + 2, pointNum); pointNum--; s.erase(s.begin() + i + 1); } else { break; } } return; } vector restoreIpAddresses(string s) { backtracking(s, 0, 0); return ans; } }; ``` # 4. 心得 1. 判断字符串s在左闭又闭区间[start, end]所组成的数字是否合法 ```cpp 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; } ``` 2. 插入逗点之后,下一子串的起始位置为i+2 3. 逗点数量为3时,分割结束 4. 递归调用时,下一层递归的startIndex要从i+2开始(因为需要在字符串中加入了分隔符'.'),同时记录分割符的数量pointNum 要 +1。 5. 回溯的时候,就将刚刚加入的分隔符. 删掉就可以了,pointNum也要-1。

栏目列表