import java.util.ArrayList;
import java.util.List;
/**
* @author xienl
* @description 数字字符串转化成IP地址
* @date 2022/7/1
*/
public class Solution {
public static void main(String[] args) {
Solution solution = new Solution();
}
String nums = "";
public ArrayList<String> restoreIpAddresses (String s) {
ArrayList<String> res = new ArrayList<>();
dfs(s, res, 0, 0);
return res;
}
private void dfs(String s, ArrayList<String> res, int step, int index ){
if (step == 4){
if (index == s.length()){
res.add(nums);
}
return;
}
String cur = "";
for (int i = index; i < index + 3 && i < s.length(); i++){
// 记录上一个结果
String temp = nums;
cur += s.charAt(i);
int num = Integer.parseInt(cur);
if (num <= 255 && (cur.length() == 1 || cur.charAt(0) != '0')){
//添加点
if(step - 3 != 0)
nums += cur + ".";
else{
nums += cur;
}
//递归查找下一个数字
dfs(s, res, step + 1, i + 1);
//回溯
nums = temp;
}
}
}
}
06-18
2149
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)