Skip to content

Commit 38e5149

Browse files
author
谢育欣
committed
done
1 parent 2bc8451 commit 38e5149

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
package com.leetcode;
2+
3+
import java.util.ArrayList;
4+
import java.util.List;
5+
6+
public class Main93_FuYuanIP {
7+
public List<String> restoreIpAddresses(String s) {
8+
if (s == null || s.length() < 4 || s.length() > 12) {
9+
return new ArrayList<>();
10+
}
11+
List<String> res = new ArrayList<>();
12+
addRes(res, s, "", 1);
13+
return res;
14+
}
15+
16+
private void addRes(List<String> res, String source, String target, int segment) {
17+
if (segment == 4) {
18+
if (source.length() < 1 || source.length() > 3 || (source.length() > 1 && source.startsWith("0")) || Integer.parseInt(source) > 255) {
19+
return;
20+
}
21+
target += source;
22+
res.add(target);
23+
return;
24+
}
25+
for (int i = 1; i <= 3; i++) {
26+
if (i >= source.length()) {
27+
break;
28+
}
29+
String currentSegment = source.substring(0, i);
30+
if (i > 1 && currentSegment.startsWith("0")) {
31+
break;
32+
}
33+
if (i == 3 && Integer.parseInt(currentSegment) > 255) {
34+
break;
35+
}
36+
String newTarget = target + currentSegment + ".";
37+
addRes(res, source.substring(i), newTarget, segment + 1);
38+
}
39+
}
40+
41+
public static void main(String[] args) {
42+
Main93_FuYuanIP main = new Main93_FuYuanIP();
43+
String s = "25525511135";
44+
System.out.println(main.restoreIpAddresses(s));
45+
}
46+
}

0 commit comments

Comments
 (0)