括号匹配的检验(利用栈实现)

目录

问题描述

代码实现(手写栈实现)

代码实现(调用STL库中的栈实现)


问题描述

假设表达式中允许包含三种括号:圆括号,方括号,花括号(大括号)。

写入一个括号序列,来判断括号序列是否匹配。

例如:

1. ( [ ] ( ) { } ) 为正确格式

2.   [ ( { } ] ) 为错误格式

3.    [ [ ] ] ] 为错误格式

若括号序列匹配正确则输出YES,否则输出NO。

代码实现(手写栈实现)

#include<bits/stdc++.h>
using namespace std;
typedef char ElemType;
typedef struct StackNode {
	ElemType data;
	struct StackNode *next;
}StackNode, *LinkStack;

//初始化栈 
bool InitStack(LinkStack &S) {
	//构造一个空栈,栈顶指针置为空 
	S = NULL; 
	return true;
}

//入栈
bool Push(LinkStack &S, ElemType e) {
	StackNode *p = new StackNode;
	p->data = e;
	p->next = S;
	S = p;
	return true;
} 

//出栈
bool Pop(LinkStack &S, ElemType &e) {
	if(!S)
		return false;
	e = S->data;
	S = S->next;
	return true;
}

bool Match(string s, LinkStack &st) {
	char ch;
	for(int i = 0; i < s.length(); i++) {
		if(s[i] == '(' || s[i] == '{' || s[i] == '[')
			Push(st, s[i]);
		else if(s[i] == ')') {
			if(!Pop(st, ch))
				return false;
			if(ch != '(')
				return false;
		}
		else if(s[i] == '}') {
			if(!Pop(st, ch))
				return false;
			if(ch != '{')
				return false;
		}
		else if(s[i] == ']') {
			if(!Pop(st, ch))
				return false;
			if(ch != '[')
				return false;
		}
	}
	if(st)
		return false;
	return true;
}

int main() {
	string s;
	LinkStack st;
	InitStack(st);
	cout << "请输入括号序列:" << endl;
	cin >> s;
	if(Match(s, st))
		cout << "YES" << endl;
	else
		cout << "NO" << endl;
	return 0;
}

代码实现(调用STL库中的栈实现)

#include<bits/stdc++.h>
using namespace std;
bool Match(string str, int length) {
	stack<char> s;
	for(int i = 0; i < length; i++) {
		if(str[i] == '(' || str[i] == '[' || str[i] == '{') {
			s.push(str[i]);
		}
		else{
			if(s.empty())
				return false;
			char ch;
			ch = s.top(); 
			s.pop(); 
			if(str[i] == ')' && ch != '(')
				return false;
			if(str[i] == ']' && ch != '[')
				return false;
			if(str[i] == '}' && ch != '{')
				return false;
		}
	}
	return s.empty();
}
int main(){
	string str;
	cin >> str;
	if(Match(str, str.size()))
		cout << "YES" << endl;
	else
		cout << "NO" << endl;
	return 0;
}

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值