class Solution {
public:
vector<string> restoreIpAddresses(string s) {
vector<string> res;
helper(s,0,3,res);
return res;
}
void helper(string s, int start, int dot, vector<string>& res)
{
if(!dot)//no more dots need to be added
{
if(s.size()-start==2&&s[start]=='0')//the last part is less than 10
return;
if(s.size()-start==3)
{
int num=(s[start]-'0')*100+(s[start+1]-'0')*10+s[start+2]-'0';
if(num<100||num>255)
return;
}
res.push_back(s);
}
for(int l=0;l<3&&start+l<s.size()-1;l++)
{
double ave=(double)(s.length()-start-l-1)/dot;
if(ave>3)//if the remaining string cannot be divided by dots
continue;
if(l==1)
{
int num=(s[start]-'0')*10+s[start+1]-'0';
if(num<10)
return;
}
else if(l==2)
{
int num=(s[start]-'0')*100+(s[start+1]-'0')*10+s[start+2]-'0';
if(num>255||num<100)
return;
}
string temp;
temp+=s.substr(0,start+l+1);
temp+='.';
temp+=s.substr(start+l+1);
helper(temp,start+l+2,dot-1,res);
}
}
};
leetcode 93: Restore IP Addresses
最新推荐文章于 2025-05-26 21:34:34 发布