数据结构之带优先级的括号匹配

要求:读取一段字符串中的括号,检测括号的左右括号是否匹配,同时还要优先级也要匹配,如小括号内如果有中括号就属于优先级不匹配

// project1.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include<stack>
#include<iostream>
using namespace std;

int priority(char bracket){
    switch(bracket){
    case '(':
        return 1;
    case '[':
        return 2;
    case '{':
        return 3;
    default:
        return -1;
    }
}

bool match(char a,char b){
    if(a=='(' && b==')')
        return true;
    else if(a=='[' && b==']')
        return true;
    else if(a=='{' && b=='}')
        return true;
    else return false;
}

bool bracket_match(char exp[]){
    char *ptr=exp;
    stack<char> stk;
    while(*ptr!=''){
        if(*ptr=='('||*ptr=='['|| *ptr=='{'){//左括号
            if(!stk.empty() && priority(stk.top())<priority(*ptr)){
                cout<<"priority error!"<<endl;
                return false;
            }
            stk.push(*ptr);
        }
        else if(*ptr==')'||*ptr==']'|| *ptr=='}'){//右括号
            if(! stk.empty() && match(stk.top(),*ptr))
                stk.pop();
            else {
                cout<<"bracket not match!"<<endl;
                return false;
            }
        }
        ptr++;
    }
    cout<<"Match!"<<endl;
    return true;
}

int _tmain(int argc, _TCHAR* argv[])
{
    char exp1[1000]="{@@$[@#@(#34)]@#@~!}sdff#f[..(dfasdfsdf)](){()}";
    char exp2[1000]="{@@$[@#@(#34)]@#@~!}sdff#f[{..(dfasdfsdf)](){()}";
    char exp3[1000]="{@@$[@#@(#34)]@#@~!}sdff#f[..(dfasdfsdf[])](){()}";
    char exp4[1000]="{@@$[@#@(#34){}]@#@~!}sdff#f[..(dfasdfsdf)](){()}";
    char exp5[1000]="{@@$[[@#@(#34)]@#@~!}sdff#f[..(dfasdfsdf)](){()}";

    bracket_match(exp1);
    bracket_match(exp2);
    bracket_match(exp3);
    bracket_match(exp4);
    bracket_match(exp5);
    
    return 0;
}



关于优先级的检测,要点在进栈时做个检查就行

原文地址:https://www.cnblogs.com/abc123456789/p/3433453.html