数据结构 - 栈 - 括号匹配

用栈来实现括号匹配。

括号匹配

假设一个算术表达式中包含圆括号、方括号两种类型的括号,试编写一个判断表达式中括号是否匹配的程序,匹配返回 Match succeed!,否则返回 Match false!

输入格式

包含圆括号、方括号两种类型括号的算术表达式。

输出格式

  • 匹配输出 Match succeed!

  • 不匹配输出 Match false!

输入输出样例

样例 1

输入

[1+2*(3+4*(5+6))]

输出

Match succeed!

样例 2

输入

(1+2)*(1+2*[(1+2)+3)

输出

Match false!

注意输入输出最后都以换行符 \n 结尾。

题解

\(\text{STL}\) 中的 \(\text{stack}\) 实现括号匹配。熟悉 \(\text{stack}\) 的使用。

#include <cstdio>
#include <cstdlib>
#include <stack>

using namespace std;

int main()
{
    char ch;
    stack<char> s;
    while ((ch = getchar()) && ch != '\n') {
        if (ch == '[' || ch == '(') {
            s.push(ch);
        }
        else if (ch == ']') {
            if (s.empty()) {
                s.push(ch); break;
            }
            else {
                if (s.top() == '[') s.pop();
                else break;
            }
        }
        else if (ch == ')') {
            if (s.empty()) {
                s.push(ch); break;
            }
            else {
                if (s.top() == '(') s.pop();
                else break;
            }
        }
    }
    if (s.empty()) printf("Match succeed!\n");
    else printf("Match false!\n");

    return 0;
}

posted on 2022-03-29 12:23  Black_x  阅读(147)  评论(0编辑  收藏  举报