class Solution {
//DFS
//Note: there are 4 special process here
public:
void DFS(int curStep, int curPos, const string& s, string& curAns, vector<string>& ans)
{
if(s.size()-curPos > (5-curStep)*3)//3. cut off, for the long number
return;
if(curPos >= s.size()) return;//4. check if it is valid
if(curStep == 4)
{
if( IsValid(curPos, s.size()-1, s) )
ans.push_back(curAns);
}
for (int i = curPos; i < s.size(); ++i)
{
if ( IsValid(curPos, i, s) )
{
curAns.insert(curAns.begin()+i+curStep, '.');
DFS(curStep+1, i+1, s, curAns, ans);
curAns.erase(curAns.begin()+i+curStep);
}
}
}
bool IsValid( int start, int end, const string& s )
{
if(s[start] == '0' && end != start)//1. 001 is not valid
return false;
if(end-start > 3)//2. len greater than 3 is also not valid, too long may cause overflow
return false;
int res = 0;
for (int i = start; i <= end; ++i)
res = res*10+s[i]-'0';
if(res <= 255)
return true;
}
vector<string> restoreIpAddresses(string s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<string> ans;
string curAns = s;
DFS(1, 0, s, curAns, ans);
return ans;
}
};
second time
class Solution {
//1. terminate case should satisfy all the conditions
//2. cut off should at leat cover the out of range case
//3. move should satisfy all the necessary conditions
public:
void restoreUtil(string& s, int curIdx, vector<int>& curPath, vector<string>& allPath)
{
if(curPath.size() == 4 && curIdx == s.size())
{
string tmp = s;
for(int i = curPath.size()-2; i >= 0; --i) tmp.insert(curPath[i]+1, 1, '.');//insert char before pos
allPath.push_back(tmp);
return;
}
if(curPath.size() >= 4 || curIdx >= s.size()) return;
int curNum = s[curIdx]-'0';
int end = curIdx;
do
{
curPath.push_back(end);
restoreUtil(s, end+1, curPath, allPath);
curPath.pop_back();
end++;
curNum = curNum*10+s[end]-'0';
}while(end < s.size() && curNum <= 255 && s[curIdx] != '0');
}
vector<string> restoreIpAddresses(string s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<int> curPath;
vector<string> allPath;
restoreUtil(s, 0, curPath, allPath);
return allPath;
}
};
本文详细介绍了两种解析IP地址的实现方法,包括深度优先搜索(DFS)和递归利用,通过验证条件来构建有效的IP地址组合。重点讨论了算法优化、边界条件判断以及如何在限制条件下生成合法的IP地址段。
808

被折叠的 条评论
为什么被折叠?



