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)
Subscribe to see which companies asked this question
分析:
三重循环,遍历三个小数点的位置,对每个位置check一下即可。
注意:
stoi函数默认要求输入的参数字符串是符合int范围的[-2147483648, 2147483647],否则会runtime error。
atoi函数则不做范围检查,若超过int范围,则显示-2147483648(溢出下界)或者2147483647(溢出上界)。
ac代码:
class Solution {
public:
vector<string> restoreIpAddresses(string s) {
vector<string>rets;
int i,j,k,L=s.length();
string ip1,ip2,ip3,ip4,ip;
if(L>12||L<4)
return rets;
for(i=1;i<L;i++)
{
for(j=i+1;j<L;j++)
{
for(k=j+1;k<L;k++)
{
ip1=s.substr(0,i);
ip2=s.substr(i,j-i);
ip3=s.substr(j,k-j);
ip4=s.substr(k,L-k);
if(check(ip1)&&check(ip2)&&check(ip3)&&check(ip4))
{
ip=ip1+"."+ip2+"."+ip3+"."+ip4;
rets.push_back(ip);
}
}
}
}
return rets;
}
bool check(string s)
{
int val=stoi(s);
if(s[0]=='0')
{
return s.length()==1;
}
else
{
if(val<=255)
return true;
else
return false;
}
}
};