F - Parentheses Balance

点我吧,我在这

题意:

输入一个包含()和[]的括号序列,判断是否合法。 

具体递归定义如下:1.空串合法;2.如果A和B都合法,则AB合法;3.如果A合法则(A)和[A]都合法。

思路:

括号匹配,栈的思想,只将左括号进栈,如果是左括号,则进栈,如是右括号,则一定与栈顶匹配,若不匹配就是错误的,且最后栈一定为空才行

#include <stdio.h>
#include <math.h>
#include <string.h>
#include <algorithm>
#include <vector>
using namespace std;
typedef long long ll;
vector <int>ve[100005];
unsigned long long a,b,k;
int main()
{
   int t,i,j;
   char s[300],a[300];
   scanf("%d",&t);
   getchar();    //吸收回车
   while(t--)
   {
      gets(s);
      if(strlen(s)==0)  //空串
      {
          printf("Yes\n");
          continue;
      }
      j=0;
      int flag=1;
      for(i=0;i<strlen(s);i++)
      {
          if(s[i]=='('||s[i]=='[')   //左括号进栈
          {
             a[j++]=s[i];
          }
          else
          {
              if(s[i]==')'&&a[j-1]==s[i]-1)  //ASCII :'(':40  ')':41
                j--;
              else if(s[i]==']'&&a[j-1]==s[i]-2)  // '[':91  ']':93
                     j--;
                   else
                    {
                       flag=0;
                       break;
                    }
          }
      }
      if(flag==0||j)  //j!=0说明左括号的数量大于右括号的数量
        printf("No\n");
      else
        printf("Yes\n");
   }
   return 0;
}

猜你喜欢

转载自blog.csdn.net/ac_ac_/article/details/80628090