给一个由数字组成的字符串。求出其可能恢复为的所有IP地址。
(你的任务就是往这段字符串中添加三个点, 使它成为一个合法的IP地址. 返回所有可能的IP地址.)
样例
样例 1:
输入: "25525511135"
输出: ["255.255.11.135", "255.255.111.35"]
解释: ["255.255.111.35", "255.255.11.135"] 同样可以.
样例 2:
输入: "1116512311"
输出: ["11.165.123.11","111.65.123.11"]
注意事项
你可以以任意顺序返回所有合法的IP地址.
解题思路:
DFS
public class Solution {
/**
* @param s: the IP string
* @return: All possible valid IP addresses
*/
public List<String> restoreIpAddresses(String s) {
// write your code here
List<String> res = new ArrayList<>();
if(s.length() < 4 || s.length() > 12)
return res;
dfs(s, new ArrayList<String>(), res, 0);
return res;
}
private void dfs(String s, List<String> list, List<String> res, int index){
//list中已经有四段数字字符串了,进入最终处理阶段
if(list.size() == 4){
if(index != s.length()) //list这四段不能组成s,如[2,5,5,2]
return;
StringBuffer sb = new StringBuffer();
for (String tmp: list) {
sb.append(tmp);
sb.append(".");
}
sb.deleteCharAt(sb.length()-1);
res.add(sb.toString());
return;
}
for(int i = index;i < s.length() && i < index + 3 ; i++){ //以index为起点向后取数字,不超过s的长度而且最多取3个
String tmp = s.substring(index, i + 1);
if(isVaild(tmp)){
list.add(tmp);
dfs(s, list, res, i + 1);
list.remove(list.size() - 1);
}
}
}
private boolean isVaild(String s){
if (s.charAt(0) == '0')
return s.equals("0"); // to eliminate cases like "00", "10"
int digit = Integer.valueOf(s);
return digit >= 0 && digit <= 255;
}
}

本文深入探讨了如何从一个由数字组成的字符串中恢复出所有可能的合法IP地址的方法。通过详细的示例和代码实现,讲解了使用深度优先搜索(DFS)算法解决此问题的策略,包括如何验证每个部分是否符合IP地址规范。
8735

被折叠的 条评论
为什么被折叠?



