-
Notifications
You must be signed in to change notification settings - Fork 1
/
TagValidator.java
82 lines (77 loc) · 2.51 KB
/
TagValidator.java
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
72
73
74
75
76
77
78
79
80
81
82
package com.hncboy;
import java.util.ArrayDeque;
import java.util.Deque;
/**
* @author hncboy
* @date 2022/5/2 14:59
* 591.标签验证器
*
* 通过次数 8,587 提交次数 17,394
*/
public class TagValidator {
public boolean isValid(String code) {
int n = code.length();
Deque<String> tags = new ArrayDeque<String>();
int i = 0;
while (i < n) {
if (code.charAt(i) == '<') {
if (i == n - 1) {
return false;
}
if (code.charAt(i + 1) == '/') {
int j = code.indexOf('>', i);
if (j < 0) {
return false;
}
String tagname = code.substring(i + 2, j);
if (tags.isEmpty() || !tags.peek().equals(tagname)) {
return false;
}
tags.pop();
i = j + 1;
if (tags.isEmpty() && i != n) {
return false;
}
} else if (code.charAt(i + 1) == '!') {
if (tags.isEmpty()) {
return false;
}
if (i + 9 > n) {
return false;
}
String cdata = code.substring(i + 2, i + 9);
if (!"[CDATA[".equals(cdata)) {
return false;
}
int j = code.indexOf("]]>", i);
if (j < 0) {
return false;
}
i = j + 1;
} else {
int j = code.indexOf('>', i);
if (j < 0) {
return false;
}
String tagname = code.substring(i + 1, j);
if (tagname.length() < 1 || tagname.length() > 9) {
return false;
}
for (int k = 0; k < tagname.length(); ++k) {
if (!Character.isUpperCase(tagname.charAt(k))) {
return false;
}
}
tags.push(tagname);
i = j + 1;
}
} else {
if (tags.isEmpty()) {
return false;
}
++i;
}
}
return tags.isEmpty();
}
}