-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathRestoreIPAddresses.kt
43 lines (39 loc) · 1.34 KB
/
RestoreIPAddresses.kt
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
/**
* Given a string containing only digits, restore it by returning all possible valid IP address combinations.
*
* For example:
* Given "25525511135",
*
* return ["255.255.11.135", "255.255.111.35"]. (Order does not matter)
*
* Accepted.
*/
class RestoreIPAddresses {
fun restoreIpAddresses(s: String): List<String> {
val results = mutableListOf<String>()
if (s.length < 4 || s.length > 12) {
return results
}
for (i in 1..3) {
for (j in 1..3) {
for (k in 1..3) {
for (m in 1..3) {
if (i + j + k + m == s.length) {
val a = s.substring(0, i).toInt()
val b = s.substring(i, j + i).toInt()
val c = s.substring(i + j, k + i + j).toInt()
val d = s.substring(i + j + k, m + i + j + k).toInt()
if (a <= 255 && b <= 255 && c <= 255 && d <= 255) {
val str = "$a.$b.$c.$d"
if (str.length == s.length + 3) {
results.add(str)
}
}
}
}
}
}
}
return results
}
}