数据结构-怀化学院期末题(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;
}
相关推荐
qqxhb1 小时前
零基础数据结构与算法——第四章:基础算法-排序(上)
java·数据结构·算法·冒泡·插入·选择
晚云与城1 小时前
【数据结构】顺序表和链表
数据结构·链表
FirstFrost --sy3 小时前
数据结构之二叉树
c语言·数据结构·c++·算法·链表·深度优先·广度优先
Yingye Zhu(HPXXZYY)3 小时前
Codeforces 2021 C Those Who Are With Us
数据结构·c++·算法
liulilittle4 小时前
LinkedList 链表数据结构实现 (OPENPPP2)
开发语言·数据结构·c++·链表
秋说5 小时前
【PTA数据结构 | C语言版】两枚硬币
c语言·数据结构·算法
☆璇6 小时前
【数据结构】栈和队列
c语言·数据结构
chao_7899 小时前
回溯题解——子集【LeetCode】二进制枚举法
开发语言·数据结构·python·算法·leetcode
秋说9 小时前
【PTA数据结构 | C语言版】将数组中元素反转存放
c语言·数据结构·算法
qqxhb11 小时前
零基础数据结构与算法——第四章:基础算法-排序(中)
数据结构·算法·排序算法·归并·快排·堆排