HTML括号匹配算法

题目

题目内容:

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

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

开标记是这种形式,闭标记是这种形式。

输入格式:

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

输出格式:

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

输入样例:

  Example   

Hello, world

输出样例:

True


思路

  1. 将其看作一个长字符串,依次读取每个字符。
  2. 遇到’<’ ‘>’ '
  3. 想要判断标签是否配对,是否有冗余的标签,标签内是否存在语法错误等。

方法

  1. 使用栈来存储标签,第一个出现的类似 前的一个标签 一定是 ,使用这个性质来进行出栈操作,若出栈失败,则存在语法结构上的错误。
  2. 当整个字符串读取完的时候,栈内还有东西,则出栈不完全,存在标签的多余,返回false;.
  3. 使用一个work工作指针,始终指向当前的正在处理的位置,遇到<> or 时,将其中标签名使用字符串操作str2(str1,a,b)(str1从a开始b个长度的字符新建为str2). 将其新建一个字符串后入栈(stack S )。

代码


/* Author : YaaaZa! 
*  Time	  : 2018.10.21
*  实现扩展括号匹配算法,用来检查HTML文档的标记是否匹配
*/

#include
#include
#include
using namespace std;
stack S;

bool haveBegin(int& begin, const string htmStr){         //检测开头第一个  <
 	for (; begin < htmStr.length(); begin++){
		if		(htmStr[begin] == ' ') continue;
		else if (htmStr[begin] == '<') return true;
		else return false;
	}
	return false;
}
bool getNext(int& work,const string htmStr) {			 //主要函数 判断在 < 后 出现的标签是否合法 是否拥有 > 收尾 若有 则进行栈操作
	int lon = work++;
	for (; work < htmStr.length(); work++) {
		if (htmStr[work] == ' ') {
			return false;
		}
		
		else if (htmStr[work] == '>') {					//有 > 号 
			string temp(htmStr, lon+1, work - lon - 1);
			if (htmStr[lon] == '/')						//如果这是一个 类似  的结束标签   则在栈顶拿 若拿不到与之一样的前置标签,则返回false
				if (S.top() == temp){
					S.pop();
					return true;
				}
				else return false;
			else {										//如果这是一个 类似  的开始标签 则入栈,返回true
				S.push(temp);
				return true;
			}
		}
		else continue;
		
	}
	return false;
}
int main(){
	string inStr;
	int numOfLeft = 0;
	int numOfRIght = 0;
	getline(cin, inStr);
	int length = inStr.length();
	int begin = 0;
	bool pass = false;
	if (haveBegin(begin,inStr)) {
		for (int work = begin; work < length; work++ ) {
			if (inStr[work] == '<' && inStr[work + 1] != '/') {   //判断是否是 
				if (getNext(work, inStr)){
					//cout << " here is a pre TAG" << endl;
					continue;
				}
				else {
					//cout << "false" << endl;
				}
			}
			else if (inStr[work] == '<' && inStr[work + 1] == '/') {
				work++;
				if (getNext(work, inStr)) {
					//cout << " here is a later TAG" << endl;
					continue;
				}
				else {
					//cout << "false" << endl;
				}
			}
			else {
				//cout << " here is a title   s" << endl;
				continue;
			}
		}
	}
	if (S.empty()) cout << "true";
		else cout <<"false";
    return 0;
}

你可能感兴趣的:(Data,Structures,题目,C++)