数据结构-怀化学院期末题(56)

括号匹配的检验

题目描述:

采用栈实现,练习进栈入栈函数的编写.

输入:

输入的第一行包含一个数,n

n表示要用例的个数

接下来是n行由括号构成的字符串,包含'('、')'、'['、']'。

输出:

对每一测试用例,用一行输出结果,如果匹配,输出"YES",否则输出"NO"

输入样例:

2

(\[\]\[\]())

)[]()

输出样例:

YES

NO

思路:

若为左括号,入栈

若为右括号

假如栈顶为空,则flag==false

否则,判断栈顶元素是否与该括号匹配,不匹配则flag==false

最后记得弹出栈顶元素

最后,判断栈是否为空,不为空,则栈中还有元素,则flag==false

代码:

cpp 复制代码
#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<string.h>
#include<algorithm>
#include<cmath>
#include<vector>
#include<queue>
#include<stack>
#include<map>
using namespace std;
typedef pair<int,int> PII;
const int N = 1e5 + 10;

int main(){
	int n;
	cin >> n;	
	while(n --){
		stack<char> s;
		string str;
		cin >> str;
		bool flag = true;
		for(int i = 0;i < str.size();i ++){
			if(str[i] == '(' || str[i] == '{' || str[i] == '['){
				s.push(str[i]);
			}
			else if(str[i] == ')' || str[i] == ']' || str[i] == '}'){
				if(s.empty()){
					flag = false;
					break;
				} 
				else{
					if(str[i] == ')'){
						if(s.top() != '(' ){
							flag = false;	
							break;
						}						
					}
					if(str[i] == ']' ){
						if(s.top() != '[' ){
							flag = false;
							break;
						}							
					}
					if(str[i] == '}' ){
						if(s.top() != '{' ){
							flag = false;
							break;
						}							
					}
				}
				s.pop();
			}			
		}
		if(!s.empty()) flag = false;
		if(flag == true) cout << "YES" << endl;
		else cout << "NO" << endl;
	}
	return 0;
}
相关推荐
CQ_07128 分钟前
自学力扣:最长连续序列
数据结构·算法·leetcode
弥彦_24 分钟前
cf1925B&C
数据结构·算法
好易学·数据结构10 小时前
可视化图解算法56:岛屿数量
数据结构·算法·leetcode·力扣·回溯·牛客网
Ashlee_code15 小时前
裂变时刻:全球关税重构下的券商交易系统跃迁路线图(2025-2027)
java·大数据·数据结构·python·云原生·区块链·perl
闻缺陷则喜何志丹16 小时前
【带权的并集查找】 P9235 [蓝桥杯 2023 省 A] 网络稳定性|省选-
数据结构·c++·蓝桥杯·洛谷·并集查找
jie*16 小时前
python(one day)——春水碧于天,画船听雨眠。
开发语言·数据结构·python·算法·线性回归
草莓熊Lotso18 小时前
【LeetCode刷题指南】--数组串联,合并两个有序数组,删除有序数组中的重复项
c语言·数据结构·其他·刷题
weixin_4196583118 小时前
数据结构之B-树
java·数据结构·b树
H_HX_xL_L18 小时前
数据结构的算法分析与线性表<1>
数据结构·算法
overFitBrain18 小时前
数据结构-2(链表)
数据结构