栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

栈在括号匹配的应用

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

栈在括号匹配的应用



当我们遇到一个左括号时,我们就把他压入栈,遇到一个右括号,就把栈顶的左括号出栈,并且检查是否与右括号匹配


当扫描到一个不匹配的,就不用继续往后扫描了,因为不管后面的,这一整个表达式括号肯定是不匹配的

还有一种情况,就是扫描到了右括号,但是栈已经空,这样子就不要在继续扫描了,因为括号肯定不匹配

还有一种情况,就是全部匹配完之后,发现栈里面还有元素,即栈非空,这样子也是不行的

#include
#define MaxSize 10
using namespace std;
typedef struct {
	char data[MaxSize];
	int top;
}SqStack;

void InitStack(SqStack& s) {
	s.top = -1;
}

bool Empty(SqStack& s) {
	if (s.top == -1) return true;
	else return false;
}

bool push(SqStack& s, char x) {
	if (s.top == MaxSize - 1) return false;
	s.top++;
	s.data[s.top] = x;
	return true;
}

bool pop(SqStack& s, char& x) {
	if (s.top == -1) return false;
	x = s.data[s.top];
	s.top--;
	return true;
}

bool pipei(char str[], int length) {
	SqStack s;
	InitStack(s);
	for (int i = 0; i < length; i++) {
		if (str[i] == '(' || str[i] == '[' || str[i] == '{') {
			push(s, str[i]);
		}
		else {//扫到右括号
			if (Empty(s)) {
				return false;
			}
			char topElem;
			pop(s, topElem);
			if (str[i] == ')' && topElem != '(') return false;
			if (str[i] == ']' && topElem != '[') return false;
			if (str[i] == '}' && topElem != '{') return false;
		}
	}
	return Empty(s);
}

int main() {
	char str[] = "((()))";
	if (pipei(str, 6)) cout << "匹配" << endl;
	else cout << "不匹配" << endl;
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/290064.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号