使用栈判断括号匹配

来源:互联网 发布:怎么在淘宝里买电棍 编辑:程序博客网 时间:2024/05/22 14:45

       判读括号是否匹配的方法比较简单,假如给定一系列的括号,判断是否全部都匹配我们肯定是将能匹配的括号全部删除,如果最后没有剩下任何括号那么肯定就是匹配了;如有剩下的左括号或者右括号说明不匹配。

       详见代码描述:

#include <iostream>#include <stack>using namespace std;int main(int argc, char const *argv[]){    string leftparenthese = "([{<";//保存左括号列表    string rightparenthese = ")]}>";//保存右括号列表    stack<char> parenthese;    string str;    cin >> str;    int flag = -1;    for (int i = 0; i < str.length(); i++)    {        if (leftparenthese.find(str[i]) != string::npos)//左括号直接入栈            parenthese.push(str[i]);        else if (rightparenthese.find(str[i]) != string::npos)//如果遇到右括号        {            //检查是否与栈顶栈顶符号匹配            if (!parenthese.empty() && leftparenthese.find(parenthese.top()) == rightparenthese.find(str[i]))                parenthese.pop();//如果匹配则删除栈顶符号            else//不匹配则标记并退出循序            {                flag = i;                break;            }        }    }    //根据比较结果判定是否匹配    if (!parenthese.empty() || flag >= 0)        cout << "unmatch" << endl;    else        cout << "perfect matched" << endl;    return 0;}


0 0
原创粉丝点击