数据结构-怀化学院期末题(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;
}
相关推荐
Fanxt_Ja2 天前
【LeetCode】算法详解#15 ---环形链表II
数据结构·算法·leetcode·链表
今后1232 天前
【数据结构】二叉树的概念
数据结构·二叉树
散1123 天前
01数据结构-01背包问题
数据结构
消失的旧时光-19433 天前
Kotlinx.serialization 使用讲解
android·数据结构·android jetpack
Gu_shiwww3 天前
数据结构8——双向链表
c语言·数据结构·python·链表·小白初步
苏小瀚3 天前
[数据结构] 排序
数据结构
睡不醒的kun3 天前
leetcode算法刷题的第三十四天
数据结构·c++·算法·leetcode·职场和发展·贪心算法·动态规划
吃着火锅x唱着歌3 天前
LeetCode 978.最长湍流子数组
数据结构·算法·leetcode
Whisper_long3 天前
【数据结构】深入理解堆:概念、应用与实现
数据结构
IAtlantiscsdn3 天前
Redis7底层数据结构解析
前端·数据结构·bootstrap