题解 | 括号的匹配

括号的匹配

https://www.nowcoder.com/practice/78f297134b0c4af09fb88218321c3fcc

#include <iostream>
#include <string>
#include <stack>
using namespace std;

int getPriority(char c) {
    switch (c) {
        case '{':
        case '}':
            return 4;
        case '[':
        case ']':
            return 3;
        case '(':
        case ')':
            return 2;
        case '<':
        case '>':
            return 1;
        default:
            return 0;
    }
}
bool isPair(char a, char b) {
    return (a == '{' && b == '}') || (a == '[' && b == ']') || (a == '(' &&
            b == ')') || (a == '<' && b == '>');
}
int main() {
    int T;
    cin >> T;
    while (T--) {
        string s;
        cin >> s;
        stack<char> st;
        bool isValid = true;
        for (char c : s) {
            if (c == '(' || c == '{' || c == '[' || c == '<') {
                if (!st.empty()) {
                    char top = st.top();
                    if (getPriority(c) > getPriority(top)) {
                        isValid = false;
                        break;
                    }
                }
                st.push(c);
            } else {
                if (st.empty()) {
                    isValid = false;
                    break;
                }
                char top = st.top();
                if (isPair(top, c)) {
                    st.pop();
                } else {
                    isValid = false;
                    break;
                }
            }
        }
        if (st.empty() && isValid) {
            cout << "YES" << endl;
        } else {
            cout << "NO" << endl;
        }
    }
    return 0;
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

溱元:前端每年固定死几次,看两集广告就复活了
点赞 评论 收藏
分享
活泼的代码渣渣在泡池...:哈哈哈挺好的,我也上岸美团了,不说了,我又接了一单
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务