题解
2025-06-22 15:30:51
发布于:浙江
1阅读
0回复
0点赞
【参考代码】
#include<iostream>
#include<string>
using namespace std;
char s[30];
int TOP;
string shabby;
void push(char x){
s[++TOP] = x;
}
void pop(){
--TOP;
}
char top(){
return s[TOP];
}
int size(){
return TOP;
}
bool empty(){
return TOP==0;
}
int main(){
cin >> shabby;
for(int i=0;i<shabby.size();i++){
if(shabby[i]=='(')push(s[i]);
if(shabby[i]==')'){
if(empty()){
cout << "NO";
return 0;
}else pop();
}
if(shabby[i]=='@')break;
}
empty() ? cout << "YES" : cout << "NO";
}
【思路分析】
定义数组 s 模拟栈,TOP 为指向栈顶的指针,初始化为0。
遍历表达式,出现 ( ,将其入栈,出现 ),将与之匹配的左括号出栈。遍历结束,如果栈是空的,说明括号匹配,否则为不匹配。
这里空空如也
有帮助,赞一个