题解 | #有效括号序列#
有效括号序列
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 } };