forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.go
64 lines (61 loc) · 1.05 KB
/
Solution.go
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
60
61
62
63
64
func validIPAddress(queryIP string) string {
if isIPv4(queryIP) {
return "IPv4"
}
if isIPv6(queryIP) {
return "IPv6"
}
return "Neither"
}
func isIPv4(s string) bool {
if strings.HasSuffix(s, ".") {
return false
}
ss := strings.Split(s, ".")
if len(ss) != 4 {
return false
}
for _, t := range ss {
if len(t) == 0 || (len(t) > 1 && t[0] == '0') {
return false
}
x := convert(t)
if x < 0 || x > 255 {
return false
}
}
return true
}
func isIPv6(s string) bool {
if strings.HasSuffix(s, ":") {
return false
}
ss := strings.Split(s, ":")
if len(ss) != 8 {
return false
}
for _, t := range ss {
if len(t) < 1 || len(t) > 4 {
return false
}
for _, c := range t {
if !unicode.IsDigit(c) && !strings.ContainsRune("0123456789abcdefABCDEF", c) {
return false
}
}
}
return true
}
func convert(s string) int {
x := 0
for _, c := range s {
if !unicode.IsDigit(c) {
return -1
}
x = x*10 + int(c-'0')
if x > 255 {
return x
}
}
return x
}