@@ -10,7 +10,8 @@ public class RestoreIPAddress {
10
10
public static void main (String [] args ) {
11
11
RestoreIPAddress obj = new RestoreIPAddress ();
12
12
String s = "25525511135" ;
13
- List <String > resultList = obj .restoreIpAddresses (s );
13
+ //List<String> resultList = obj.restoreIpAddresses(s);
14
+ List <String > resultList = obj .restoreIpAddressesWithIterate (s );
14
15
System .out .println (Arrays .toString (resultList .toArray ()));
15
16
}
16
17
@@ -32,7 +33,7 @@ private void dfs(List<String> resultList, String s, int start, String stored, in
32
33
resultList .add (stored );
33
34
}
34
35
35
- if (start = = s .length () || count == 4 ) {
36
+ if (start > = s .length () || count == 4 ) {
36
37
return ;
37
38
}
38
39
@@ -47,4 +48,43 @@ private void dfs(List<String> resultList, String s, int start, String stored, in
47
48
dfs (resultList , s , start + i , stored + part + (count == 3 ? "" : "." ), count + 1 );
48
49
}
49
50
}
51
+
52
+
53
+ public List <String > restoreIpAddressesWithIterate (String s ) {
54
+ List <String > resultList = new ArrayList <String >();
55
+ if (s == null || s .length () < 4 ) {
56
+ return resultList ;
57
+ }
58
+
59
+ int len = s .length ();
60
+ String splitS = "." ;
61
+ // iterate
62
+ for (int fisrt = 1 ; fisrt < 4 && fisrt < len - 2 ; fisrt ++) {
63
+ for (int second = fisrt + 1 ; second < fisrt + 4 && second < len - 1 ; second ++) {
64
+ for (int third = second + 1 ; third < second + 4 && third < len ; third ++) {
65
+ String part1 = s .substring (0 , fisrt );
66
+ String part2 = s .substring (fisrt , second );
67
+ String part3 = s .substring (second , third );
68
+ String part4 = s .substring (third );
69
+ if (valideIP (part1 ) && valideIP (part2 ) && valideIP (part3 ) && valideIP (part4 )) {
70
+ String result = part1 + splitS + part2 + splitS + part3 + splitS + part4 ;
71
+ resultList .add (result );
72
+ }
73
+ }
74
+ }
75
+
76
+ }
77
+
78
+ return resultList ;
79
+ }
80
+
81
+ private Boolean valideIP (String part ) {
82
+ if (part .length () == 0 || part .length () > 3
83
+ || (part .startsWith ("0" ) && part .length () != 1 )
84
+ || (part .length () == 3 && Integer .valueOf (part ) > 255 )) {
85
+ return false ;
86
+ }
87
+
88
+ return true ;
89
+ }
50
90
}
0 commit comments