-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathValidate an IP Address.java
More file actions
53 lines (40 loc) · 1.16 KB
/
Validate an IP Address.java
File metadata and controls
53 lines (40 loc) · 1.16 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
import java.util.*;
import java.io.*;
public class validip {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while (t-- > 0) {
String s = sc.next();
Solution obj = new Solution();
if (obj.isValid(s))
System.out.println(1);
else
System.out.println(0);
}
}
}// } Driver Code Ends
// User function Template for Java
class Solution {
public Set<String> allnums;
public boolean isValid(String s) {
allnums = new HashSet<>();
// allowed segments
for (int i = 0; i < 256; i++) {
allnums.add(String.valueOf(i));
}
int dots = 0;
// counting dots
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '.') dots++;
}
if (dots != 3) return false;
// split according to positions of '.'
String[] nums = s.split("\\.");
if (nums.length != 4) return false;
for (String x : nums) {
if (!allnums.contains(x)) return false;
}
return true;
}
}