题解 | #有效括号序列#

有效括号序列

https://www.nowcoder.com/practice/37548e94a270412c8b9fb85643c8ccc2

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

class Solution {
  public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param s string字符串
     * @return bool布尔型
     */
    bool isValid(string s) {
    if (s.empty() || s.size() % 2 != 0) {
        return false;
    }

    stack<char> mystack;
    char* str = &s[0];
    while(*str!='\0'){
    if (*str == '(' || *str == '{' || *str == '[') {
        mystack.push(*str);
        str++;
    }

    if (*str == ')' || *str == '}' || *str == ']') {
        if (mystack.empty()) {
            return false; // 右括号多余左括号的情况
        }
        if ((mystack.top() == '(' && *str == ')') ||
            (mystack.top() == '{' && *str == '}') ||
            (mystack.top() == '[' && *str == ']')) {
            mystack.pop(); // 匹配成功,弹出栈顶元素
            str++;
        } else {
            return false; // 不匹配的情况
        }
    }
    }
    return mystack.empty(); // 如果栈为空,说明所有括号都有匹配的,返回true;否则返回false
}

        
};

全部评论

相关推荐

点赞 评论 收藏
分享
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
06-24 20:25
腾讯今年实习招了这么多人,后面秋招还会招人吗??想着秋招再战来着
牛客965593684号:腾讯好像2020年之后就是实习生招得多,应届生基本上不招,纯实习转正
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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