目录
题目:
代码(首刷看解析 2024年2月3日):
class Solution {
public:
vector<string> res;
bool Enligible(string& s, int left, int right) {
if (left > right) return false;
if (s[left] == '0' && left != right) return false;
int num = 0;
for (int i = left; i <= right; ++i) {
if (s[i] - '0' > 9 || s[i] - '0' < 0) return false;
num = num * 10 + (s[i] - '0');
if (num > 255) return false;
}
return true;
}
void backtracking(string& s, int startIndex, int pointNubmber) {
if (pointNubmber == 3) {
if (Enligible(s, startIndex, s.size() - 1)) res.push_back(s);
return;
}
for (int i = startIndex; i < s.size(); ++i) {
if (Enligible(s, startIndex, i)) {
s.insert(s.begin() + i + 1, '.');
pointNubmber++;
backtracking(s, i + 2, pointNubmber);
pointNubmber--;
s.erase(s.begin() + i + 1);
} else {
break;
}
}
return;
}
vector<string> restoreIpAddresses(string s) {
if (s.size() < 4) return res;
backtracking(s, 0, 0);
return res;
}
};
哎,自己写的代码错误一堆
代码(二刷自解 2024年5月22日)
时间复杂度比较高,可以采用简单的dfs做法,下次试试
class Solution {
public:
vector<string> res;
vector<string> path;
bool helper(string s, int left, int right) {
string temp = s.substr(left, right - left + 1);
// 去除前置0情况
if (temp.size() > 1 && temp[0] == '0') return false;
int digit = std::stoi(temp);
//cout<<"string :"<<temp<<" int :"<<digit<<endl;
if (digit >= 0 && digit <= 255) return true;
return false;
}
void backtracking(string s, int startIndex) {
if (path.size() > 4) return;
if (path.size() == 4 && startIndex >= s.size()) {
string temp = "";
for (int i = 0; i < path.size(); i++) {
temp += path[i];
temp += ".";
}
temp.pop_back();
res.push_back(temp);
return;
}
for (int i = startIndex; i < s.size(); i++) {
if (i - startIndex > 3) break;
if (helper(s, startIndex, i)) {
path.push_back(s.substr(startIndex, i - startIndex + 1));
} else continue;
backtracking(s, i + 1);
path.pop_back();
}
}
vector<string> restoreIpAddresses(string s) {
if (s.size() < 4 || s.size() > 12) return res;
backtracking(s, 0);
return res;
}
};
代码(三刷看解析 2024年8月9日)
class Solution {
private:
vector<string> res;
bool valid(string& s, int start, int end) const {
if (start > end || end - start >= 3) {
return false;
}
// 有前导0
if (s[start] == '0' && start != end) {
return false;
}
// 判断是否在0-255之间
int digit = 0;
for (int i = start; i <= end; i++) {
if (s[i] < '0' || s[i] > '9') {
return false;
}
digit = digit * 10 + (s[i] - '0');
}
if (digit >= 0 && digit <= 255) return true;
return false;
}
void backtracking(string& s, int startIndex, int pointNum) {
// 满足条件加入结果数组
if (3 == pointNum && valid(s, startIndex, s.size() - 1)) {
res.push_back(s);
return;
}
for (int i = startIndex; i < s.size(); i++) {
if (valid(s, startIndex, i)) {
s.insert(s.begin() + i + 1, '.');
pointNum++;
backtracking(s, i + 2, pointNum);
pointNum--;
s.erase(i + 1, 1);
}
}
}
public:
vector<string> restoreIpAddresses(string s) {
res.clear();
backtracking(s, 0, 0);
return res;
}
};