-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathValidateIPAddress.java
72 lines (62 loc) · 1.96 KB
/
ValidateIPAddress.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
68
69
70
71
72
package com.smlnskgmail.jaman.leetcodejava.medium;
import java.util.HashSet;
import java.util.Set;
// https://leetcode.com/problems/validate-ip-address/
public class ValidateIPAddress {
private static final Set<Character> CHARS_IPv6 = new HashSet<>();
static {
String availableChars = "0123456789abcdefABCDEF";
for (int i = 0; i < availableChars.length(); i++) {
CHARS_IPv6.add(availableChars.charAt(i));
}
}
private final String input;
public ValidateIPAddress(String input) {
this.input = input;
}
public String solution() {
if (input.chars().filter(c -> c == '.').count() == 3) {
return validateIPv4(input);
}
if (input.chars().filter(c -> c == ':').count() == 7) {
return validateIPv6(input);
}
return "Neither";
}
private String validateIPv4(String ip) {
String[] nums = ip.split("\\.", -1);
for (String num : nums) {
int length = num.length();
if (length == 0 || length > 3) {
return "Neither";
}
if (num.charAt(0) == '0' && length > 1) {
return "Neither";
}
for (int i = 0; i < length; i++) {
if (!Character.isDigit(num.charAt(i))) {
return "Neither";
}
}
if (Integer.parseInt(num) > 255) {
return "Neither";
}
}
return "IPv4";
}
private String validateIPv6(String ip) {
String[] parts = ip.split(":", -1);
for (String part : parts) {
int length = part.length();
if (length == 0 || length > 4) {
return "Neither";
}
for (int i = 0; i < length; i++) {
if (!CHARS_IPv6.contains(part.charAt(i))) {
return "Neither";
}
}
}
return "IPv6";
}
}