0%

468. 验证IP地址

468. 验证IP地址

模拟

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
class Solution {
public:
string validIPAddress(string queryIP) {
int mode = 3;
int begin = 0;
int n = queryIP.size();
int count = 0;
for(int i = 0; i <= n; ++i)
{
if((i == n && mode == 2) || queryIP[i] == ':')
{
if(mode == 1)
return "Neither";
mode = 2;
if(!checkIPV6(queryIP, begin, i))
return "Neither";
begin = i + 1;
++count;
}else if((i == n && mode == 1) || queryIP[i] == '.')
{
if(mode == 2)
return "Neither";
mode = 1;
if(!checkIPV4(queryIP, begin, i))
return "Neither";
begin = i + 1;
++count;
}
}
return mode == 2 ? (count == 8 ? "IPv6" : "Neither") : (count == 4 ? "IPv4" : "Neither");
}
private:
bool checkIPV4(string& ip, int start, int end)
{
if(end == start)
return false;
if(end - start == 1)
return isDigital(ip[start]);
if(ip[start] == '0')
return false;
int num = 0;
for(int i = start; i < end; ++i)
{
if(!isDigital(ip[i]))
return false;
num = num * 10 + ip[i] - '0';
if(num > 255)
return false;
}
return true;
}
bool checkIPV6(string& ip, int start, int end)
{
if(end - start > 4 || end - start == 0)
return false;
for(int i = start; i < end; ++i)
{
if(!isHex(ip[i]))
return false;
}
return true;
}
bool isDigital(char ch)
{
return ch >= '0' && ch <= '9';
}
bool isHex(char ch)
{
return isDigital(ch) || (ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F');
}
};