File tree Expand file tree Collapse file tree 1 file changed +62
-0
lines changed Expand file tree Collapse file tree 1 file changed +62
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Time: O(1)
2
+ // Space: O(1)
3
+
4
+ class Solution {
5
+ public:
6
+ string validIPAddress (string IP) {
7
+ stringstream ss (IP);
8
+ string block;
9
+ if (IP.substr (0 , 4 ).find (' .' ) != string::npos) {
10
+ for (int i = 0 ; i < 4 ; ++i) {
11
+ if (!getline (ss, block, ' .' ) || !isValidIPv4Block (block)) {
12
+ return " Neither" ;
13
+ }
14
+ }
15
+ if (ss.eof ()) {
16
+ return " IPv4" ;
17
+ }
18
+ } else if (IP.substr (0 , 5 ).find (' :' ) != string::npos) {
19
+ for (int i = 0 ; i < 8 ; ++i) {
20
+ if (!getline (ss, block, ' :' ) || !isValidIPv6Block (block)) {
21
+ return " Neither" ;
22
+ }
23
+ }
24
+ if (ss.eof ()) {
25
+ return " IPv6" ;
26
+ }
27
+ }
28
+
29
+ return " Neither" ;
30
+ }
31
+
32
+ private:
33
+ bool isValidIPv4Block (const string& block) {
34
+ int num = 0 ;
35
+ if (block.size () > 0 && block.size () <= 3 ) {
36
+ for (int i = 0 ; i < block.size (); ++i) {
37
+ char c = block[i];
38
+ if (!isalnum (c) || (i == 0 && c == ' 0' && block.size () > 1 )) {
39
+ return false ;
40
+ } else {
41
+ num *= 10 ;
42
+ num += c - ' 0' ;
43
+ }
44
+ }
45
+ return num <= 255 ;
46
+ }
47
+ return false ;
48
+ }
49
+
50
+ bool isValidIPv6Block (const string& block) {
51
+ if (block.size () > 0 && block.size () <= 4 ) {
52
+ for (int i = 0 ; i < block.size (); ++i) {
53
+ char c = block[i];
54
+ if (!isxdigit (c)) {
55
+ return false ;
56
+ }
57
+ }
58
+ return true ;
59
+ }
60
+ return false ;
61
+ }
62
+ };
You can’t perform that action at this time.
0 commit comments