括号匹配(有点复杂,因为它讲得详细)

#include<iostream>
#include<stack>
using namespace std;
void BracketMatch(char *str)
{
    stack<char> S;
    char ch;
    int i;

    for(i=0;str[i]!='\0';i++)
    {
        switch(str[i])
        {
        case'(':
        case'[':
        case'{':
            S.push(str[i]);
            break;
        case')':
        case']':
        case'}':
            if(S.empty())
            {
                printf("右括号多余\n");
                return;
            }
            else
            {
                ch=S.top();
                if((ch=='('&&str[i]==')')||(ch=='['&&str[i]==']')||(ch=='{'&&str[i]=='}'))
                    S.pop();
                else
                {
                    printf("对应的左右括号不同类\n");
                    return;
                }
            }
        }
    }
    if(S.empty())
        printf("括号匹配\n");
    else    
        printf("左括号多余\n");
}
int main()
{
    char str[134];
    while(scanf("%s",str)!=EOF)
        BracketMatch(str);
    return 0;
}
原文地址:https://www.cnblogs.com/heqinghui/p/2620293.html