Skip to content

Commit a5b0f21

Browse files
authored
Create 591.Tag Validator.cpp
1 parent a8c9363 commit a5b0f21

1 file changed

Lines changed: 96 additions & 0 deletions

File tree

Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
class Solution {
2+
public:
3+
bool isValid(string code)
4+
{
5+
stack<string>Stack;
6+
int i=0;
7+
bool cdata_flag=0;
8+
int ever=0;
9+
10+
while (i<code.size())
11+
{
12+
cout<<code[i];
13+
14+
if (cdata_flag==0 && i+9<code.size() && code.substr(i,9)=="<![CDATA[")
15+
{
16+
cdata_flag=1;
17+
i+=9;
18+
continue;
19+
}
20+
21+
if (cdata_flag==1)
22+
{
23+
if (i+3<code.size() && code.substr(i,3)=="]]>")
24+
{
25+
cdata_flag=0;
26+
i+=3;
27+
continue;
28+
}
29+
else
30+
{
31+
i++;
32+
continue;
33+
}
34+
}
35+
36+
if (code[i]=='<' && i+1<code.size() && code[i+1]!='/')
37+
{
38+
i++;
39+
int i0=i;
40+
while (code[i]!='>') i++;
41+
if (i==code.size()) return false;
42+
43+
string tag = code.substr(i0,i-i0);
44+
if (validTagName(tag)==false)
45+
return false;
46+
else if (Stack.empty() && i0!=1)
47+
return false;
48+
else
49+
{
50+
Stack.push(tag);
51+
ever=1;
52+
}
53+
i++;
54+
continue;
55+
}
56+
57+
if (code[i]=='<' && i+1<code.size() && code[i+1]=='/')
58+
{
59+
i+=2;
60+
int i0=i;
61+
while (code[i]!='>') i++;
62+
if (i==code.size()) return false;
63+
64+
string tag = code.substr(i0,i-i0);
65+
if (Stack.empty() || Stack.top()!=tag)
66+
return false;
67+
else if (Stack.size()==1 && i!=code.size()-1)
68+
return false;
69+
else
70+
Stack.pop();
71+
i++;
72+
continue;
73+
}
74+
75+
i++;
76+
77+
78+
}
79+
80+
if (Stack.empty() && ever==1)
81+
return true;
82+
else
83+
return false;
84+
85+
}
86+
87+
bool validTagName(string tag)
88+
{
89+
if (tag.size()==0 || tag.size()>9) return false;
90+
for (int i=0; i<tag.size(); i++)
91+
{
92+
if (tag[i]>'Z' || tag[i]<'A') return false;
93+
}
94+
return true;
95+
}
96+
};

0 commit comments

Comments
 (0)