L93: Restore IP Addresses
Given a string containing only digits, restore it by returning all possible valid IP address combinations.
For example:
Given “25525511135”,
return [“255.255.11.135”, “255.255.111.35”]. (Order does not matter)
解题思路:数据量不大,直接三重循环解决,也可以用DFS解决,差不多
class Solution {
public:
bool isIpNum(string I)
{
if(I[0] == ‘0‘ && I.length() != 1)
return false;
int num = std::stoi(I);
if(num >= 0 && num <= 255)
return true;
return false;
}
vector<string> restoreIpAddresses(string s) {
vector<string> result;
int len=s.length();
if(len<4||len>12)
return result; //肯定不满足,直接返回
string I1,I2,I3,I4;
//三重循环
for(int j=1;j<len-2;j++)
{
for(int k=j+1;k<len-1;k++)
{
for(int t=k+1;t<len;t++)
{
I1 = s.substr(0,j);
I2 = s.substr(j,k-j);
I3 = s.substr(k,t-k);
I4 = s.substr(t,len-k);
if(isIpNum(I1)&&isIpNum(I2)&&isIpNum(I3)&&isIpNum(I4))
{
string IP;
IP = I1+"."+I2+"."+I3+"."+I4;
result.push_back(IP);
}
}
}
}
return result;
}
};
Leetcode题解(2):L93/Restore IP Addresses
原文地址:http://blog.csdn.net/kzq_qmi/article/details/46381297