-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathLeetCode_00093.java
More file actions
41 lines (37 loc) · 1.15 KB
/
LeetCode_00093.java
File metadata and controls
41 lines (37 loc) · 1.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package com.github.jerring.leetcode;
import java.util.ArrayList;
import java.util.List;
public class LeetCode_00093 {
public List<String> restoreIpAddresses(String s) {
List<String> res = new ArrayList<>();
if (s == null || s.length() < 4 || s.length() > 12) {
return res;
}
dfs(s, res, new StringBuilder(), 0, 0);
return res;
}
private void dfs(String s, List<String> res, StringBuilder ip, int index, int cnt) {
if (cnt == 4) {
if (index == s.length()) {
res.add(ip.toString());
}
return;
}
for (int i = 1; i < 4; ++i) {
int end = index + i;
if (end > s.length()) {
break;
}
String sub = s.substring(index, end);
if ((sub.startsWith("0") && sub.length() > 1) || Integer.parseInt(sub) > 255) {
break;
}
if (cnt < 3) {
sub += ".";
}
ip.append(sub);
dfs(s, res, ip, end, cnt + 1);
ip.delete(ip.length() - sub.length(), ip.length());
}
}
}