-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathrestoreIpAddresses.go
More file actions
59 lines (51 loc) · 1.2 KB
/
Copy pathrestoreIpAddresses.go
File metadata and controls
59 lines (51 loc) · 1.2 KB
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
53
54
55
56
57
58
59
/* https://leetcode.com/problems/restore-ip-addresses/description/
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)
*/
package lbacktracking
import (
"strconv"
"strings"
)
func restoreIpAddresses(s string) []string {
var helper func(s string, part int) [][]string
helper = func(s string, part int) [][]string {
res := [][]string{}
if length := len(s); length < part || length > part*3 {
return res
}
validate := func(s string) bool {
if len(s) > 1 && s[0] == '0' {
return false
}
if num, _ := strconv.Atoi(s); num > 255 {
return false
}
return true
}
if part == 1 {
if validate(s) {
res = append(res, []string{s})
}
} else {
for i := 1; i <= 3 && i <= len(s); i++ {
strNum := s[:i]
if !validate(strNum) {
continue
}
for _, sub := range helper(s[i:], part-1) {
res = append(res, append([]string{strNum}, sub...))
}
}
}
return res
}
ips := helper(s, 4)
res := make([]string, len(ips))
for i, ip := range ips {
res[i] = strings.Join(ip, ".")
}
return res
}