STL实现括号匹配

来源:互联网 发布:大数据领域ml是什么 编辑:程序博客网 时间:2024/06/09 16:37

//括号匹配,利用STL中的栈来实现,对(,[,{入栈操作,其余采用出栈操作
#include<iostream>
#include<stack>
using namespace std;
int judge( char a )
{
 switch (a)
 {
 case '[':
 case '{':
 case '(':
  return 1;
 default:
  return 0;
 }
}

char match( char a )
{
 switch(a)
 {
 case '{':
  return '}';
 case '[':
  return ']';
 case '(':
  return ')';
 }
}

int main()
{
 char A[10] = {0};
 gets(A);
 stack<char> S;
 int i = 0;
 while(A[i]!='\0')
 {  
  if( judge(A[i])==1 )
   S.push(A[i]);
  else
  {  
   if(match(S.top())==A[i])
   {
    S.pop();
   }
   else
   {
    printf("Wrong\n");
    return 0;
   }
  }
  i++;
 }
 
 printf("Right\n");
 
 return 0;
}