数据结构-怀化学院期末题(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;
}
相关推荐
pzx_0011 分钟前
【内积】内积计算公式及物理意义
数据结构·python·opencv·算法·线性回归
重生之我要进大厂4 小时前
LeetCode 876
java·开发语言·数据结构·算法·leetcode
Happy鱿鱼4 小时前
C语言-数据结构 有向图拓扑排序TopologicalSort(邻接表存储)
c语言·开发语言·数据结构
KBDYD10105 小时前
C语言--结构体变量和数组的定义、初始化、赋值
c语言·开发语言·数据结构·算法
Crossoads5 小时前
【数据结构】排序算法---桶排序
c语言·开发语言·数据结构·算法·排序算法
QXH2000005 小时前
数据结构—单链表
c语言·开发语言·数据结构
imaima6665 小时前
数据结构----栈和队列
开发语言·数据结构
David猪大卫6 小时前
数据结构修炼——顺序表和链表的区别与联系
c语言·数据结构·学习·算法·leetcode·链表·蓝桥杯
Iceberg_wWzZ6 小时前
数据结构(Day14)
linux·c语言·数据结构·算法
Beauty.5686 小时前
P1328 [NOIP2014 提高组] 生活大爆炸版石头剪刀布
数据结构·c++·算法