Given a string containing only digits, restore it by returning all possible valid IP address combinations.
Example:
Input: "25525511135"
Output: ["255.255.11.135", "255.255.111.35"]
题解:递归判断是不是合法ip,用index表示当前串的指针,注意前置0的处理然后当cnt达到4时加入ans中,刚开始时在判断当前子串第一个位置是否为0时用了子串的index实际上是给出的串。。
代码:
class Solution {
public:
vector<string> restoreIpAddresses(string s) {
vector<string> ans;
dfs(s,"",0,0,ans);
return ans;
}
void dfs(string s,string ip,int index,int cnt,vector<string>& ans){
if(cnt>4)return;
if(cnt==4 && index==s.size())ans.push_back(ip);
for(int i=index;i<index+3;i++){
if(i>=s.size())break;
string str=s.substr(index,i-index+1);
if((str.size()>1&&s[index]=='0')||(i-index>=2&&(int)stoi(str)>=256))
continue;
dfs(s,ip+str+(cnt==3?"":"."),i+1,cnt+1,ans);
}
}
};
class Solution {
public:
vector<string> restoreIpAddresses(string s) {
vector<string> ans;
for(int a=1;a<=3;a++)
for(int b=1;b<=3;b++)
for(int c=1;c<=3;c++)
for(int d=1;d<=3;d++){
if(a+b+c+d==s.size()){
int A=stoi(s.substr(0,a));
int B=stoi(s.substr(a,b));
int C=stoi(s.substr(a+b,c));
int D=stoi(s.substr(a+b+c,d));
if(A<=255&&B<=255&&C<=255&&D<=255){
string tmp=to_string(A)+'.'+to_string(B)+'.'+to_string(C)+'.'+to_string(D);
if(tmp.size()==s.size()+3) ans.push_back(tmp);
}
}
}
return ans;
}
};