题目:
Given a string containing only digits, restore it by returning all possible valid IP address combinations.
A valid IP address consists of exactly four integers (each integer is between 0 and 255) separated by single points.
Example:
Input: "25525511135"
Output: ["255.255.11.135", "255.255.111.35"]
使用不同的分割方法列举所有可能情况,判断分割是否有效,若有效则记录
代码如下:
class Solution {
public:
bool isVaildIP(string s)
{
if(s.length() > 3 || s.length() == 0 || (s.length() > 1 && s[0] == '0') || atoi(s.c_str()) > 255 )
{
return false;
}
return true;
}
vector<string> restoreIpAddresses(string s) {
int len = s.length();
vector<string> res;
for(int i = 1; i < 4 && i < len - 2; i++)
{
for(int j = i + 1; j < i + 4 && j < len - 1; j++)
{
for(int k = j + 1; k < j + 4 && k < len; k++)
{
string s1 = s.substr(0,i);
string s2 = s.substr(i,j-i);
string s3 = s.substr(j,k-j);
string s4 = s.substr(k,len-k);
if(isVaildIP(s1) && isVaildIP(s2) && isVaildIP(s3) && isVaildIP(s4))
{
res.push_back(s1 + "." + s2 + "." + s3 + "." + s4);
}
}
}
}
return res;
}
};