-
Notifications
You must be signed in to change notification settings - Fork 3
/
591.cpp
53 lines (53 loc) · 1.82 KB
/
591.cpp
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
class Solution {
public:
bool isValidTag(string& tag) {
if (tag.size() < 1 || tag.size() > 9) return false;
for (auto c : tag) {
if (c < 'A' || c > 'Z') return false;
}
return true;
}
bool isValid(string code) {
int index = 0;
bool hasTag = false;
int n = code.size();
stack<string> st;
while (index < n) {
if (index + 8 < n && code.substr(index, 9) == "<![CDATA[") {
index += 9;
while (index + 2 < n && code.substr(index, 3) != "]]>") {
index++;
}
if (index == n) return false;
index += 3;
}
else if (index + 1 < n && code.substr(index, 2) == "</") {
index += 2;
int start = index;
while (index < n && code[index] != '>') index++;
if (index == n) return false;
string tagName = code.substr(start, index - start);
if (st.empty() || st.top() != tagName) return false;
st.pop();
index += 1;
if (st.empty() && index != n) return false;
}
else if (code[index] == '<') {
index += 1;
int start = index;
while (index < n && code[index] != '>') index++;
if (index == n) return false;
string tagName = code.substr(start, index - start);
if (!hasTag && start != 1) return false;
hasTag = true;
if (!isValidTag(tagName)) return false;
st.push(tagName);
index++;
}
else index++;
}
if (!st.empty()) return false;
if (!hasTag) return false;
return true;
}
};