0%

468. Validate IP Address

O(n) time
这道题2001:0db8:85a3:00:000:8A2E:0370:7334是合法的

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
class Solution {
public:
string validIPAddress(string IP) {
if (isIPv4(IP)) return "IPv4";
else if (isIPv6(IP)) return "IPv6";
return "Neither";
}

bool isIPv4(const string &IP) {
if (count(begin(IP), end(IP), '.') != 3) return false;
istringstream input(IP);
string s;
int cnt = 0;
while (getline(input, s, '.')) { // 分段检查
try {
int x = stoi(s);
if (to_string(x) != s || x < 0 || x > 255) return false; // 开头不能有0,必须在0到255之间,不能有非数字
} catch (exception &e) {
return false;
}
++cnt;
}
return cnt == 4;
}

bool isIPv6(const string &IP) {
if (count(begin(IP), end(IP), ':') != 7) return false;
istringstream input(IP);
string s;
int cnt = 0;
while (getline(input, s, ':')) { // 分段检查
if (empty(s) || size(s) > 4) return false;
for (char c : s) {
c = tolower(c);
if (!('0' <= c && c <= '9') && !('a' <= c && c <= 'f')) return false; // 不能有非16进制字符
}
++cnt;
}
return cnt == 8;
}
};
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
class Solution {
public:
string validIPAddress(string IP) {
if (IP.empty() || IP.back() == '.' || IP.back() == ':') return "Neither"; // 不能结尾出现delimiter
bool isv4 = false;
for (char c : IP) {
if (isv4 = c == '.') break; // 初步判断是v4还是v6
}
char delimiter = isv4 ? '.' : ':';
int cnt = 0;
istringstream input(IP);
string s;
while (getline(input, s, delimiter)) { // 分段检查
if (!isValid(s, isv4)) return "Neither";
++cnt; // 数一共有几段
}
if (isv4) { // 判断段数是否合法
return cnt == 4 ? "IPv4" : "Neither";
} else {
return cnt == 8 ? "IPv6" : "Neither";
}
}

bool isValid(const string &s, bool isv4) {
if (isv4) {
if (s.empty() || s.length() > 3) return false; // 判断长度
int x = 0;
for (char c : s) {
if (!isdigit(c)) return false; // 判断是否有非法字符比如abcd
x = x * 10 + c - '0';
}
return (s == "0") || (0 < x && x < 256 && s[0] != '0'); // 不能出现leading zeros
} else {
if (s.empty() || s.length() > 4) return false;
for (char c : s) {
c = tolower(c);
if (!('0' <= c && c <= '9') && !('a' <= c && c <= 'f')) return false;
}
return true;
}
}
};