/*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)
*/
#include <vector>
#include <string>
#include <iostream>
#include <algorithm>
class Solution
{
public:
std::vector<std::string> restoreIpAddresses(std::string s)
{
std::string::iterator l1,l2,l3;
std::string str1,str2,str3,str4;
std::vector<std::string> vec;
for(int i=1;i<=3;++i)
{
l1=s.begin()+i;
str1=std::string(s.begin(),l1);
if(!isValid(str1))
continue;
for(int j=1;j<=3;++j)
{
l2=l1+j;
str2=std::string(l1,l2);
if(!isValid(str2))
continue;
for(int t=1;t<=3;++t)
{
l3=l2+t;
if(l3>=s.end())
break;
str3=std::string(l2,l3);
str4=std::string(l3,s.end());
if(!isValid(str3) || !isValid(str4))
continue;
vec.push_back(str1+"."+str2+"."+str3+"."+str4);
}
}
}
return vec;
}
private:
bool isValid(const std::string& sub)
{
if(sub.size()==1)
return true;
else if(sub.size()==2 && sub[0]!='0')
return true;
else if(sub.size()==3 && sub[0]>='1' && sub[0]<='2')
{
if(sub[0]=='2' &&((sub[1]=='5' && sub[2]>'5')||(sub[1]>'5')))
return false;
return true;
}
return false;
}
};
int main(int argc,char* argv[])
{
std::string str("172162541");
Solution s;
std::vector<std::string> vec=s.restoreIpAddresses(str);
std::for_each(vec.begin(),vec.end(),[](const std::string& s)
{
std::cout<<s<<std::endl;
}
);
return 0;
}
字符串解析出所有ip地址
最新推荐文章于 2025-04-29 09:22:12 发布