forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
67 lines (64 loc) · 1.69 KB
/
Solution.java
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
65
66
67
class Solution {
public String validIPAddress(String queryIP) {
if (isIPv4(queryIP)) {
return "IPv4";
}
if (isIPv6(queryIP)) {
return "IPv6";
}
return "Neither";
}
private boolean isIPv4(String s) {
if (s.endsWith(".")) {
return false;
}
String[] ss = s.split("\\.");
if (ss.length != 4) {
return false;
}
for (String t : ss) {
if (t.length() == 0 || t.length() > 1 && t.charAt(0) == '0') {
return false;
}
int x = convert(t);
if (x < 0 || x > 255) {
return false;
}
}
return true;
}
private boolean isIPv6(String s) {
if (s.endsWith(":")) {
return false;
}
String[] ss = s.split(":");
if (ss.length != 8) {
return false;
}
for (String t : ss) {
if (t.length() < 1 || t.length() > 4) {
return false;
}
for (char c : t.toCharArray()) {
if (!Character.isDigit(c)
&& !"0123456789abcdefABCDEF".contains(String.valueOf(c))) {
return false;
}
}
}
return true;
}
private int convert(String s) {
int x = 0;
for (char c : s.toCharArray()) {
if (!Character.isDigit(c)) {
return -1;
}
x = x * 10 + (c - '0');
if (x > 255) {
return x;
}
}
return x;
}
}