思路:递归求解,记录点数,如果超过了3个点(IP地址中),而且当前位置已经到了字符串的最后一个位置,则说明分割完成,只要每个部分的数都在255以内,则可以作为一个解。注意 10.00.10.1 这种格式是不允许的,在中间过程加以判断。
code:
class Solution {
public:
void solve(int pointNum,int start,string s,string curS, vector<string> &ret){
if(pointNum > 3){
if(start >= s.length())
ret.push_back(curS);
return;
}
for(int i = 1;i<=3;i++){
if(start + i <= s.length()){
string temp = s.substr(start,i);
int curNum = atoi(temp.c_str());
if(temp[0] == '0' && temp.length() > 1)
continue;
if(curNum <= 255){
string tempS = curS;
if(pointNum >= 1)
tempS += ".";
tempS += temp;
solve(pointNum+1,start+i,s,tempS,ret);
}
}
}
}
vector<string> restoreIpAddresses(string s) {
vector<string> ret;
string tempS;
solve(0,0,s,tempS,ret);
return ret;
}
};