C++利用堆栈判断字符串中括号是否匹配

  • Stack(栈)是一种后进先出的数据结构,也就是LIFO(last in first out) ,最后加入栈的元素将最先被取出来,在栈的同一端进行数据的插入与取出,这一段叫做“栈顶”。通过利用这种性质可以判断字符串中括号是否匹配。

  • 使用STL的stack需要include一个头文件<stack>

  • c++ stl栈stack的成员函数介绍

    • pop() 移除栈顶元素
    • empty() 堆栈为空则返回真
    • push() 在栈顶增加元素
    • size() 返回栈中元素数目
    • top() 返回栈顶元素
#include <iostream>
#include <stack>
#include <string>

using namespace std;

bool valid_braces(std::string braces) {
    // valid or not valid?
    stack<char> char_stack;
    bool        ans = true;
    int         i;
    for (auto c : braces) {
        if (c == '{' || c == '(' || c == '[') {
            char_stack.push(c);
        } else {
            if (char_stack.empty()) {
                ans = false;
                break;
            } else if ((c == '}' && char_stack.top() == '{') || (c == ')' && char_stack.top() == '(') || (c == ']' && char_stack.top() == '[')) {
                char_stack.pop();
            } else {
                ans = false;
                break;
            }
        }
    }
    if (!char_stack.empty()) {
        ans = false;
    }
    return ans;
}


int main(int argc, char* argv[]) {
    string braces_str;
    cout << "Please enter braces string:";
    cin >> braces_str;
    cout << valid_braces(braces_str);
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章