题目内容:
实现扩展括号匹配算法,用来检查HTML文档的标记是否匹配。
HTML标记应该成对、嵌套出现,
开标记是<tag>这种形式,闭标记是</tag>这种形式。
输入格式:
共1行,为一个字符串,即一个HTML文档中的内容。
输出格式:
共1行,为True或者False,表示该字符串中的标记是否匹配。
输入样例:
<html> <head> <title>Example</title> </head> <body> <h1>Hello, world</h1> </body> </html>
输出样例:
True
C++版
#include <iostream>
#include<cstdio>
#include<algorithm>
#include <cstring>
#include<stack>
#include <string>
#include<math.h>
#define MAX 210
using namespace std;
bool is_match(string str)
{
int size_length=str.size();
stack<string> s,result;
for (int i = 0; i < size_length; ++i)
{ bool find=false;
if (str[i]=='<')
{ string temp;
while(str[i]!='>')
{ if(str[i]=='/')
{
find=true;
i++;
continue;
}
temp+=str[i];
i++;
}
temp+=str[i];
if(find)
{
string com1=s.top();
// cout<<temp<<" "<<com1;
if(com1!=temp)
return false;
else
s.pop();
}
else{
s.push(temp);
// cout<<s.top()<<endl;
}
}
}
if(!result.empty())return false;
else return true;
}
int main(int argc, char const *argv[])
{
string str;
getline(cin,str);
if(is_match(str))cout<<"True";
else cout<<"False";
return 0;
}
Python 版
from pythonds.basic.deque import Deque
class Stack:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[len(self.items)-1]
def size(self):
return len(self.items)
def HTMLMatch(s):
s=s.split()
element=''
temp=''
deq=Deque()
stack=Stack()
for i in s:
flag=False
for j in i:
if j=='<':
flag=True
continue
elif j=='>':
flag=False
element+=' '
if flag:
element+=j
temp=element.split()
for str in temp:
deq.addFront(str)
element=''
Match=True
stack.push(deq.removeRear())
while not deq.isEmpty() and Match:
a='/'+''.join(stack.peek())
b=deq.removeRear()
if a!=''.join(b):
stack.push(b)
else:
stack.pop()
if not stack.isEmpty():
Match=False
return Match
# 请在此编写你的代码(可删除pass语句)
# 代码结束
# 调用检验
print("3-HTMLMatch")
print(HTMLMatch("<html> <head> <title>Example</title> </head> <body> <h1>Hello, world</h1> </body> </html>"))