数据结构-怀化学院期末题(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;
}
相关推荐
杰克尼7 小时前
BM5 合并k个已排序的链表
数据结构·算法·链表
xiaolang_8616_wjl8 小时前
c++文字游戏_闯关打怪
开发语言·数据结构·c++·算法·c++20
hqxstudying9 小时前
Java创建型模式---单例模式
java·数据结构·设计模式·代码规范
sun0077009 小时前
数据结构——栈的讲解(超详细)
数据结构
ゞ 正在缓冲99%…14 小时前
leetcode918.环形子数组的最大和
数据结构·算法·leetcode·动态规划
努力写代码的熊大15 小时前
单链表和双向链表
数据结构·链表
Orlando cron16 小时前
数据结构入门:链表
数据结构·算法·链表
许愿与你永世安宁21 小时前
力扣343 整数拆分
数据结构·算法·leetcode
Heartoxx1 天前
c语言-指针(数组)练习2
c语言·数据结构·算法
杰克尼1 天前
1. 两数之和 (leetcode)
数据结构·算法·leetcode