文章

3

粉丝

294

获赞

0

访问

20.7k

头像
利用map将括号的优先级表示出来
P1067 中山大学2019年机试题
发布于2021年3月13日 20:35
阅读数 7.7k

#include<bits/stdc++.h>
using namespace std;

bool bracketCheck(char str[])
{
    int length=strlen(str);
    stack<char> s;
    map <char ,int> t; //定义map 通过值来直观比较优先级
    t['{']=4;
    t['[']=3;
    t['(']=2;
    t['<']=1;
    for(int i=0;i<length;i++)
    {
        if(str[i]=='<'|| str[i]=='('|| str[i]=='{'||str[i]=='[')
        {
            
            if(!s.empty())
            {
                char top;
            top=s.top();
            if(t[str[i]]>t[top]) 
            return false;
            }
         
            s.push(str[i]);
            
        }
        else{
            if(s.empty()) return false;
        
    char top;
    top=s.top();
    s.pop();
    
    if(str[i]==')'&& top!='(')
    return false;
    if(str[i]==']'&& top!='[') 
    return false;
    if(str[i]=='}'&& top!='{') 
    return false;
    if(str[i]=='>'&& top!='<')
    return false;
...
登录查看完整内容


登录后发布评论

暂无评论,来抢沙发