【OJ】html标记匹配

…衆ロ難τιáo~ 提交于 2019-12-01 07:14:42

题目内容:

实现扩展括号匹配算法,用来检查HTML文档的标记是否匹配。

HTML标记应该成对、嵌套出现,

开标记是<tag>这种形式,闭标记是</tag>这种形式。

 

输入格式:

共1行,为一个字符串,即一个HTML文档中的内容。

 

输出格式:

共1行,为True或者False,表示该字符串中的标记是否匹配。

 

输入样例:

<html> <head> <title>Example</title> </head> <body> <h1>Hello, world</h1> </body> </html>

 

输出样例:

True

 1 #include <iostream>
 2 #include <stack>
 3 #include <string>
 4 using namespace std;
 5 int main(){
 6     stack<string> my_tag;
 7     int sign = 0, flag = 0;
 8     string my_html, tmp;
 9     getline(cin, my_html);
10     for (int i = 0, j = 0; i < my_html.length(); ++i, ++j){
11         if (my_html[i] == '<'){
12             sign = i + 1;
13             j = 0;
14             if (my_html[sign] == '/')
15                 flag = 1;
16             else
17                 flag = 0;
18         }
19         if (my_html[i] == '>'){
20             if (flag == 0){
21                 tmp.assign(my_html, sign, j - 1);
22                 my_tag.push(tmp);
23             }
24             else{
25                 tmp.assign(my_html, sign + 1, j - 1);
26                 if (tmp.compare(my_tag.top())){
27                     my_tag.pop();
28                     continue;
29                 }
30                 else{
31                     cout << "False" << endl;
32                     return 0;
33                 }
34                     
35             }
36         }
37     }
38     if (my_tag.empty())
39         cout << "True" << endl;
40     else
41         cout << "False" << endl;
42     return 0;
43 }

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!