leetcode-restore-ip-addresses

题目大意

  https://leetcode.com/problems/restore-ip-addresses/

  给你一个只含数字的字符串,输出所有的ip地址可能情况。

题目分析

  简单的DFS,注意一下边界条件,递归时注意分三种情况,地址是3位,2位,1位整数进行枚举

代码

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
42
43
44
45
46
47
48
49
50
51
52
public class Solution {
private List<String> ans;
private int[] path;
private char[] c;
private int len;
private void search(int idx, int step) {
// 边界条件
if (step == 4) {
if (idx == len) {
StringBuilder sb = new StringBuilder();
sb.append(path[0]);
for (int i = 1; i < 4; i++) {
sb.append(".");
sb.append(path[i]);
}
ans.add(sb.toString());
}
return;
}
// 3位
if ((len - idx) >= (3 - step + 3) && c[idx] >= '1' && c[idx] <= '2') {
int sum = 100 * (c[idx] - '0') + 10 * (c[idx + 1] - '0') + c[idx + 2] - '0';
if (sum <= 255) {
path[step] = sum;
search(idx + 3, step + 1);
}
}
// 2位
if ((len - idx) >= (3 - step + 2) && c[idx] > '0') {
path[step] = 10 * (c[idx] - '0') + c[idx + 1] - '0';
search(idx + 2, step + 1);
}
// 1位
if ((len - idx) >= (3 - step + 1)) {
path[step] = c[idx] - '0';
search(idx + 1, step + 1);
}
}
public List<String> restoreIpAddresses(String s) {
c = s.toCharArray();
len = c.length;
ans = new ArrayList<String>();
path = new int[4];
if (len < 4 || len > 12) {
return ans;
}
search(0, 0);
return ans;
}
}