题目:
A valid IP address consists of exactly four integers separated by single dots. Each integer is between 0
and 255
(inclusive) and cannot have leading zeros.
- For example,
"0.1.2.201"
and"192.168.1.1"
are valid IP addresses, but"0.011.255.245"
,"192.168.1.312"
and"192.168@1.1"
are invalid IP addresses.
Given a string s
containing only digits, return all possible valid IP addresses that can be formed by inserting dots into s
. You are not allowed to reorder or remove any digits in s
. You may return the valid IP addresses in any order.
Example 1:
Input: s = "25525511135" Output: ["255.255.11.135","255.255.111.35"]
Example 2:
Input: s = "0000" Output: ["0.0.0.0"]
Example 3:
Input: s = "101023" Output: ["1.0.10.23","1.0.102.3","10.1.0.23","10.10.2.3","101.0.2.3"]
Constraints:
1 <= s.length <= 20
s
consists of digits only.
思路:
找出合理的IP地址,本质是回溯的分割字符串,只是加上了一些小的字符串处理。显然“ . ”符号只能有三个,那么递归的case就是当符号出现三个时,就跳出,在跳出前判断第三个符号后面到整个字符串结尾能否成为合理的IP数字。这个判断我们另写一个函数,如果开始点大于结束点,说明已经是"233.233.233."这种情况,那么肯定是不可以的;0前导也是不可以的;并且数字要在[0, 255]。之后就是标准回溯,如果当前子串符合条件,那么就进行下一轮回溯递归。
代码:
class Solution {
public:
vector<string> restoreIpAddresses(string s) {
backtracking(s, 0, 0);
return res;
}
private:
vector<string> res;
bool check(string& s, int start, int end) {
if (start > end)
return false;
string tmp = s.substr(start, end - start + 1);
if (tmp.size() > 1 && tmp[0] == '0')
return false;
if (tmp.size() > 3)
return false;
int ans = stoi(tmp);
if (ans < 0 || ans > 255)
return false;
return true;
}
void backtracking(string &s, int index, int count) {
if (count == 3) {
if (check(s, index, s.size() - 1)) {
res.push_back(s);
}
return;
}
for (int i = index; i < s.size(); i++) {
if (check(s, index, i)) {
s.insert(begin(s) + i + 1, '.');
backtracking(s, i + 2, count + 1);
s.erase(begin(s) + i + 1);
}
}
}
};