forked from rui-yan/LeetCode-1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tag-validator.cpp
70 lines (64 loc) · 1.63 KB
/
tag-validator.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
// Time: O(n)
// Space: O(n)
class Solution {
public:
bool isValid(string code) {
auto i = 0;
return validTag(code, &i) && i == code.length();
}
private:
bool validTag(const string& s, int *i) {
auto j = *i;
auto tag = parseTagName(s, &j);
if (tag.empty()) {
return false;
}
parseContent(s, &j);
auto k = j + tag.size() + 2;
if (k >= s.size() || s.substr(j, k + 1 - j) != "</" + tag + ">") {
return false;
}
*i = k + 1;
return true;
}
string parseTagName(const string& s, int *i) {
if (s[*i] != '<') {
return "";
}
auto j = s.find('>', *i);
if (j == string::npos || j - 1 - *i < 1 || 9 < j - 1 - *i) {
return "";
}
auto tag = s.substr(*i + 1, j - 1 - *i);
for (const auto& c : tag) {
if (c < 'A' || 'Z' < c) {
return "";
}
}
*i = j + 1;
return tag;
}
void parseContent(const string& s, int *i) {
while (*i < s.size()) {
if (!validText(s, i) && !validCData(s, i) && !validTag(s, i)) {
break;
}
}
}
bool validText(const string& s, int *i) {
auto j = *i;
*i = s.find("<", *i);
return *i != j;
}
bool validCData(const string& s, int *i) {
if (s.find("<![CDATA[", *i) != *i) {
return false;
}
auto j = s.find("]]>", *i);
if (j == string::npos) {
return false;
}
*i = j + 3;
return true;
}
};