SWUST OJ 962 括号匹配问题

题目

假设表达式中允许包含两种括号:圆括号和方括号。编写一个算法判断表达式中的括号是否正确配对。
输入由括号构成的字符串,包含”(“、”)“、”[“和”]“。输出如果匹配输出YES,否则输出NO。

样例输入

[([])]

样例输出

YES

分析

AC代码

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<stack>
#include<string>
using namespace std;
char arr;
int main()
{
  stack<char>st;
  while(scanf("%c",&arr)&&arr!='\n')
  {
   if(st.empty())
   {
    st.push(arr);
    continue;
 }
   if((arr==']'&&st.top()=='[')||(arr==')'&&st.top()=='('))
    st.pop();
    else
    st.push(arr);
  }
  if(st.empty())
  cout<<"YES";
  else
  cout<<"NO";
}
发布了52 篇原创文章 · 获赞 22 · 访问量 1730

猜你喜欢

转载自blog.csdn.net/qq_45792080/article/details/104583113