Leetcode(93) Restore IP Addresses

Description

Given a string containing only digits, restore it by returning all possible valid IP address combinations.

Example:

1
2
Input: "25525511135"
Output: ["255.255.11.135", "255.255.111.35"]

解法

暴力搜索三个点的位置,然后对分割后的ip进行检测即可。

注意check函数的写法

具体代码如下:

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
class Solution {
public List<String> restoreIpAddresses(String s) {
List<String> res = new ArrayList<>();
String ip1, ip2, ip3, ip4;
if (s.length() > 12) {
return res;
}
for (int i = 0; i < s.length(); i++) {
for (int j = i + 1; j < s.length(); j++) {
for (int k = j + 1; k < s.length() - 1; k++) {
ip1 = s.substring(0, i + 1);
ip2 = s.substring(i + 1, j + 1);
ip3 = s.substring(j + 1, k + 1);
ip4 = s.substring(k + 1);
if (check(ip1) && check(ip2) && check(ip3) && check(ip4)) {
String ip = ip1 + "." + ip2 + "." + ip3 + "." + ip4;
res.add(ip);
}
}
}
}

return res;
}

Boolean check(String ip) {
int val = Integer.parseInt(ip);
if (ip.charAt(0) == '0') {
return ip.length() == 1;
}
return val <= 255;
}
}