花了差不多一個晚上找bug,將
string tmpString;
tmpString += s[start + 0] + s[start + 1] + s[start + 2];
改為
string tmpString;
tmpString.push_back(s[start + 0]);tmpString.push_back(s[start + 1]);tmpString.push_back(s[start + 2]);
程序就正常了,什麼原因!!!
class Solution {
public:
void backtracking(string s, int start, int depth, vector &result, string &output, int length) {
if(start >= length)
return;
if(depth == 3) {
if(length - start > 3)
return;
if(length - start == 1) {
output.push_back(s[start]);
result.push_back(output);
output.pop_back();
return;
}
if( length - start == 2) {
if(s[start] != '0') {
output.push_back(s[start]);output.push_back(s[start + 1]);
result.push_back(output);
output.pop_back();output.pop_back();
return;
}else {
return;
}
}
if( length - start == 3) {
if(s[start] != '0') {
string tmpString;
tmpString.push_back(s[start + 0]);tmpString.push_back(s[start + 1]);tmpString.push_back(s[start + 2]);
int tmpInt = stoi(tmpString);
if(tmpInt > 255) {
return;
}else {
output.push_back(s[start]);output.push_back(s[start + 1]);output.push_back(s[start + 2]);
result.push_back(output);
output.pop_back();output.pop_back();output.pop_back();
return;
}
}else {
return;
}
}
}
output.push_back(s[start + 0]);output.push_back('.');
backtracking(s, start + 1, depth + 1, result, output, length);
output.pop_back();output.pop_back();
if((s[start] != '0') && (length - start >= 2)) {
output.push_back(s[start + 0]); output.push_back(s[start + 1]);output.push_back('.');
backtracking(s, start + 2, depth + 1, result, output, length);
output.pop_back(); output.pop_back();output.pop_back();
}
if((s[start] != '0') && (length - start >= 3)) {
string tmpString;
tmpString.push_back(s[start + 0]);tmpString.push_back(s[start + 1]);tmpString.push_back(s[start + 2]);
int tmpInt = stoi(tmpString);
if(tmpInt > 255) {
return;
}else {
output.push_back(s[start + 0]);output.push_back(s[start + 1]);output.push_back(s[start + 2]);output.push_back('.');
backtracking(s, start + 3, depth + 1, result, output, length);
output.pop_back();output.pop_back();output.pop_back();output.pop_back();
}
}
}
vector restoreIpAddresses(string s) {
vector result;
string output;
int length = s.size();
backtracking(s, 0, 0, result, output, length);
return result;
}
};