题目描述
现在有一个只包含数字的字符串,将该字符串重新存储成IP地址的形式,返回所有可能的情况。
例如:
给出的字符串为"25525511135",
返回["255.255.11.135", "255.255.111.35"]. (顺序没有关系)
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)
示例1
输出
复制["255.255.11.135","255.255.111.35"] class Solution {
public:
/**
*
* @param s string字符串
* @return string字符串vector
*/
vector<string> restoreIpAddresses(string s) {
// write code here1
vector<string > result;
string t;
DFS(result,t,s,0);
return result;
}
void DFS(vector< string> &result,string t,string s, int count){
if (count==3 && isValid(s)){
result.push_back(t+s);
return ;
}
for (int i=1;i<4 && i<s.size();i++){
string sub=s.substr(0,i);
if (isValid(sub))
DFS(result,t+sub+'.',s.substr(i),count+1);
}
}
bool isValid(string &s){
stringstream ss(s);
int num;
ss>>num;
if (s.size()>1)
return s[0] !='0' &&num>=0 && num<=255;
return num>=0 && num<=255;
}
};