练习3 - 字符串匹配问题(strs)

本文深入探讨了一种用于检查括号、尖括号等符号是否正确配对的算法。通过使用栈数据结构,该算法能够有效地验证输入字符串中各种成对符号的正确闭合情况,确保代码的语法正确性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


#include <iostream>
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<math.h>
#include<sstream>
using namespace std;
#define L 101
int top=0;	
char a[L];	//栈
char b; 
int len = 0;
bool flag = true;
int i=0;	//升级变量 
char pushA[L][L]={{},{'<'},{'<','('},{'<','(','['}};	//
void push(int n)
{
	for(int i=0;i<n;i++){
		//遍历检查 
		if(a[top]==pushA[n][i]){
			flag = false;
			return;
		} 
	}
	a[++top] = b;
	//a[++top] = b[i];
}
char popA[L+50];
void pop(){
	if(a[top]!=popA[int(b)]) flag = false;
	else top--;
}
int main()
{	
	//输入数据 
	cin >> len;
	//初始化map
	popA[int('>')] = '<';
	popA[int(')')] = '(';
	popA[int(']')] = '[';
	popA[int('}')] = '{';
	for(i=0;i<len;i++){
		cin >> b;	//覆盖字符 
		if(flag){
			//也可以用map 
			switch(b){
			case '<':
				push(0);break; 
			case '(':
				push(1);break; 
			case '[':
				push(2);break;
			case '{':
				push(3);break;
			default:{
				pop();
			}
		}
		}else{
			cout << "NO";
			break;	
		}
	}//上面还未有结果 => 还可能有剩余 
	if(flag){
		if(top>0) cout << "NO";
		else cout << "YES";
	}

	return 0;
}
//cout << "输入:"

结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值