Skip to content

Commit 59f46c8

Browse files
committed
feat(): 模拟
1 parent 936427e commit 59f46c8

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

string/468/solution1.js

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
/**
2+
* 时间复杂度:O(n)
3+
* 空间复杂度:O(1)
4+
*/
5+
const isDigit = (str) => !Number.isNaN(Number.parseInt(str, 10));
6+
7+
const validIPAddress = queryIP => {
8+
if (queryIP.indexOf('.') >= 0) {
9+
let last = -1;
10+
for (let i = 0; i < 4; i++) {
11+
const current = i === 3 ? queryIP.length : queryIP.indexOf('.', last + 1);
12+
13+
if (current < 0 || current - last - 1 < 1 || current - last - 1 > 3) {
14+
return 'Neither';
15+
}
16+
17+
let address = 0;
18+
for (let j = last + 1; j < current; j++) {
19+
if (!isDigit(queryIP[j])) {
20+
return 'Neither';
21+
}
22+
address = address * 10 + (queryIP[j].charCodeAt() - '0'.charCodeAt());
23+
}
24+
25+
if (address > 255 || (address > 0 && queryIP[last + 1].charCodeAt() === '0'.charCodeAt()) || (address === 0 && current - last - 1 > 1)) {
26+
return 'Neither';
27+
}
28+
last = current;
29+
}
30+
return 'IPv4';
31+
}
32+
33+
let last = -1;
34+
for (let i = 0; i < 8; i++) {
35+
const current = (i === 7 ? queryIP.length : queryIP.indexOf(':', last + 1));
36+
if (current < 0 || current - last - 1 < 1 || current - last - 1 > 4) {
37+
return "Neither";
38+
}
39+
for (let j = last + 1; j < current; ++j) {
40+
if (!isDigit(queryIP[j]) && !('a' <= queryIP[j].toLowerCase() && queryIP[j].toLowerCase() <= 'f')) {
41+
return "Neither";
42+
}
43+
}
44+
last = current;
45+
}
46+
47+
return 'IPv6';
48+
}

0 commit comments

Comments
 (0)