括号匹配问题 ← 栈

【问题描述】
本题来源于严蔚敏《数据结构(C语言版 第2版)》之双色版的第74页,并进行了简单扩展。
题目大意为:给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 等括号的字符串,判断其中的括号是否匹配。若匹配,输出 true。否则,输出 false。(注意,空字符串被认为是匹配的字符串)

【输入样例】
()
[]
()[]{}
(]

([)]

【输出样例】
true
true
true
false
true
false


【算法分析】
此题算法给出了利用顺序栈求解相关问题的模板,值得探究学习。其中:
初始时栈顶指针根据需要设为 
top=-1;,这也是判断栈为空的条件。
入栈操作语句为 
s[++top]=…;
出栈操作语句为 top--;
输出栈顶元素语句为 cout<<s[top];

【算法代码】

#include <bits/stdc++.h>
using namespace std;

const int maxn=100;
char st[maxn];
int top=-1;

bool ismeet(char u,char v) {
	if(u=='(' && v==')') return true;
	if(u=='[' && v==']') return true;
	if(u=='{' && v=='}') return true;
	return false;
}

int main() {
	string s;
	while(getline(cin,s)) {
		if(s.empty()) cout<<"true"<<endl; //Empty strings match by default
		else {
			st[++top]=s[0];
			for(int i=1; i<s.size(); i++) { //Judge from the second character
				if(top!=-1 && ismeet(st[top],s[i])) top--;
				else st[++top]=s[i];
			}
			
			if(top==-1) cout<<"true"<<endl;
			else cout<<"false"<<endl;
		}
	}
	return 0;
}


/*
input:
()
[]
()[]{}
(]

([)]

output:
true
true
true
false
true
false
*/


【参考文献】
https://blog.csdn.net/smallrain6/article/details/113197402



 





 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值