题解 | 数字字符串转化成IP地址
数字字符串转化成IP地址
https://www.nowcoder.com/practice/ce73540d47374dbe85b3125f57727e1e
class Solution {
public:
vector<string> res;
string res_son;
string ss;
void dfs(int depth, int idx){
if(depth>3){
if(idx!=ss.length())
return ;
res.push_back(res_son);
}
else{
string curr = "";
for(int i=idx; i<idx+3 && i<ss.size(); i++){
curr += ss[i];
int num = stoi(curr); // 用于判断是否满足条件
string temp = res_son; // 用于回退时候用
if(num<=255 && (curr.length()==1|| curr[0]!='0')){
if(depth-3!=0)
res_son += curr + '.';
else
res_son += curr;
dfs(depth+1, i+1);
res_son = temp;
}
}
}
}
vector<string> restoreIpAddresses(string s) {
ss = s;
dfs(0, 0);
return res;
}
};
// 用伪代码写一下解题思路:
vector<string> res;
string res_son;// 用来表示某个答案。
void dfs(深度depth,当前第几个字符idx){
如果深度到了4,则:
case1:idx还没到最后,则return;
case2:idx也到最后了,则将res_son push到res数组中,作为一个解;
如果深度没到4,则:
string curr="";// 表示当前string类型的数字
for (i in idx+1~3){//因为字段最多也就是3个数组成
curr += s[i];
int num = 转数字函数(curr);
string temp=res_son;// 暂存当前的res_son,之后回退的时候直接把temp赋值回去即可。
if (num满足:0~255;curr满足没有前导'0')则{
将curr加到res_son后面,且视情况在后面加入'.';
dfs(depth+1,i+1);
回退,curr_son=temp。
}
} // end for
}
