forked from wisdompeak/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path591.Tag Validator.cpp
More file actions
95 lines (84 loc) · 2.58 KB
/
Copy path591.Tag Validator.cpp
File metadata and controls
95 lines (84 loc) · 2.58 KB
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
83
84
85
86
87
88
89
90
91
92
93
94
95
class Solution {
public:
bool isValid(string code)
{
stack<string>TagStack;
int i=0;
bool cdata_flag=0;
bool ever=0;
while (i<code.size())
{
if (cdata_flag==0 && i+9<=code.size() && code.substr(i,9)=="<![CDATA[")
{
cdata_flag=1;
i+=9;
continue;
}
if (cdata_flag==1)
{
if (i+3<=code.size() && code.substr(i,3)=="]]>")
{
cdata_flag=0;
i+=3;
continue;
}
else
{
i++;
continue;
}
}
if (code[i]=='<' && i+1<code.size() && code[i+1]!='/')
{
i++;
int i0=i;
while (i<code.size() && code[i]!='>') i++;
if (i==code.size()) return false;
string TagName=code.substr(i0,i-i0);
if (validTagName(TagName)==false)
return false;
else if (TagStack.empty() && i0-1!=0) // must start with a tag
return false;
else
{
TagStack.push(TagName);
ever=1;
}
i++;
continue;
}
if (code[i]=='<' && i+1<code.size() && code[i+1]=='/')
{
i+=2;
int i0=i;
while (i<code.size() && code[i]!='>') i++;
if (i==code.size()) return false;
string TagName=code.substr(i0,i-i0);
if (TagStack.empty() || TagStack.top()!=TagName)
return false;
else if (TagStack.size()==1 && i<code.size()-1) // must end with a tag
return false;
else
TagStack.pop();
i++;
continue;
}
i++;
}
if (TagStack.empty() && ever==1)
return true;
else
return false;
}
bool validTagName(string t)
{
if (t=="") return false;
if (t.size()>9) return false;
for (int i=0; i<t.size(); i++)
{
if (t[i]<'A' || t[i]>'Z')
return false;
}
return true;
}
};