原创牛客网算法—名企高频面试题143题(16)
程序员文章站
2022-06-19 11:40:36
93. 复原IP地址class Solution { List res = new ArrayList<>(); public List restoreIpAddresses(String s) { List segment = new ArrayList<>(); //开始搜索 dfs(s, 0, segment);...
class Solution {
List<String> res = new ArrayList<>();
public List<String> restoreIpAddresses(String s) {
List<String> segment = new ArrayList<>();
//开始搜索
dfs(s, 0, segment);
return res;
}
private void dfs(String s, int start, List<String> segment) {
if (start == s.length()) {
if (segment.size() == 4) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < segment.size(); i++) {
sb.append(segment.get(i));
if (i != segment.size() - 1) sb.append('.');
}
res.add(sb.toString());
}
return;
} else {
if (segment.size() >= 4) return;
for (int i = start; i < s.length() && i < start + 3; i++) {
String str = s.substring(start, i + 1);
if (str.charAt(0) == '0' && str.length() > 1) break;
int num = Integer.parseInt(str);
if (num >= 0 && num <= 255) {
segment.add(str);
dfs(s, i + 1, segment);
segment.remove(segment.size() - 1);
} else {
break;
}
}
}
}
}
本文地址:https://blog.csdn.net/weixin_41605937/article/details/111943014
上一篇: mysql高效查询left join和group by(加索引)
下一篇: 13张扑克牌的顺序