栈 || 括号匹配(基础版)

来源:互联网 发布:mac 抹掉磁盘步骤 编辑:程序博客网 时间:2024/06/01 08:34
#include <iostream>#include <cstdio>#include <stack>#include <map>using namespace std;map<char,char> m;/** 括号匹配的四种可能性:    ①左右括号配对次序不正确    ②右括号多于左括号    ③左括号多于右括号    ④左右括号匹配正确*/void init(){    m[']'] = '[';    m['}'] = '{';    m[')'] = '(';}int check(char c){    if( c=='(' || c=='{' ||c=='['  )        return 1;    else if( c==')' || c=='}' ||c==']')        return 2;    return 0;}bool brackets(string str){    int len = str.length();    stack<char> s;    for( int i =0 ; i < len; ++i )    {        int t = check(str[i]);        if( t == 0)            continue;        else if( t==1 )            s.push(str[i]);        else        {            if( s.empty()  || (s.top()!=m[str[i]]) )//右括号多或者栈顶不匹配                return false;            else s.pop();//栈顶匹配        }    }    if( s.empty())        return true;//完全匹配    return false;//左括号多}int main(){    init();    string s;    while(cin>>s)    {        if(brackets(s))            puts("Yes");        else            puts("No");    }    return 0;}

0 0
原创粉丝点击