GEEK编程练习— —有效括号问题

来源:互联网 发布:mac chill 试色 编辑:程序博客网 时间:2024/06/08 01:28

题目

给定一个字符串只包含(,),{,},[和],判断输入是否合法。括号必须按照正确顺序排列,如()和()[]是合法的,而(]和([)]不合法。

输入

()[]

输出

True

输入

[)]

输出

False

分析

利用栈stack的特性。

代码

#include <iostream>#include <string>#include <stack>using namespace std;int main(){    string str;    cin >> str;    string left = "([{";    string right = ")]}";    stack<char> stk;    for (auto c : str)    {        if (left.find(c) != string::npos)        {            stk.push (c);        }        else        {            if (stk.empty () || stk.top () != left[right.find (c)])            {                cout << "False" << endl;                return 0;            }            else            {                stk.pop ();            }        }    }    if (stk.empty())    {        cout << "True" << endl;    }    return 0;}
0 0