题解 | #有效括号序列#
有效括号序列
https://www.nowcoder.com/practice/37548e94a270412c8b9fb85643c8ccc2
#include <string> #include <type_traits> class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param s string字符串 * @return bool布尔型 */ bool left (char s){ return (s=='('||s=='['||s=='{'); } bool right(char s){ return (s==')'||s==']'||s=='}'); } bool check(char a,char b){//检查左右括号是否匹配 return (a=='('&&b==')')||(a=='['&&b==']')||(a=='{'&&b=='}'); } bool isValid(string s) { stack <char>p; int i=0; while(i<s.size()){ if(left(s[i])){//遇到左括号压栈 p.push(s[i]); } else if(right(s[i])){ if(!p.empty()&&check(p.top(), s[i])) {//遇到右括号时栈不为空且栈顶元素匹配当前元素,出栈 p.pop(); } else { return false; } } i++; } if(!p.empty()){//遍历结束后栈空且没有发生错误,则匹配成功,否则失败 return false; } return true; } };