题解 | 有效括号序列
有效括号序列
https://www.nowcoder.com/practice/37548e94a270412c8b9fb85643c8ccc2
C++ ①左括号入栈(if else)
class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param s string字符串 * @return bool布尔型 */ bool isValid(string s) { // write code here stack<char> a; if (s.size()%2) return false; else { for (int i=0; i<s.size(); ++i) { char b = s[i]; if (b=='[' || b=='(' || b=='{') { a.push(b); //左括号入栈 } else { if (a.empty()) return false; char c = a.top(); if (b==']' && c=='[') a.pop(); else if (b==')' && c=='(') a.pop(); else if (b=='}' && c=='{') a.pop(); else return false; } } } if (a.empty()) return true; else return false; } };
②右括号入栈(case)
class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param s string字符串 * @return bool布尔型 */ bool isValid(string s) { // write code here stack<char> a; if (s.size()%2) return false; else { for (int i=0; i<s.size(); ++i) { switch (s[i]) { case '[': a.push(']'); break; // 可以没{},但是一定要break case '(': a.push(')'); break; case '{': a.push('}'); break; default: // case 后面只能判断常量 const变量也不行 if (a.size() && (a.top()==s[i])) a.pop(); else return false; break; } } } if (a.empty()) return true; else return false; } };