要注意各种细节
class Solution {
private:
vector<string> ans;
public:
bool isValid(const string& s, int start, int end){
// if (s.size() > 3)
// return false;
if ((end - start + 1) > 3){
return false;
}
if (start > end)
return false;
if (start != end && s[start] == '0')
return false;
int num = 0;
for (int i = start; i <= end; i++){//这里是小于等于
// for (int i = end; i >= start; --i){
if (s[i] < '0' || s[i] > '9')
return false;
num = num * 10 + (s[i] - '0');
if(num > 255)
return false;
}
//return num <= 255;
return true;
}
vector<string> restoreIpAddresses(string s) {
if (s.size() > 12)
return ans;
backtracing(s, 0, 0);
return ans;
}
void backtracing(string& s, int startIndex, int pointNum){
if (pointNum == 3){
if(isValid(s, startIndex, s.size()-1))
ans.push_back(s);
return ;
}
for (int i = startIndex; i < s.size(); i++){
if (isValid(s, startIndex, i)){
s.insert(s.begin() + i + 1, '.');
pointNum++;
//backtracing(s, i+1, pointNum);
backtracing(s, i+2, pointNum);
pointNum--;
s.erase(s.begin() + i + 1);
}//else continue;
else break;
}
}
};