class Solution { public: /** * * @param s string字符串 * @return bool布尔型 */ bool isValid(string s) { // write code here stack<char> stack1; for (int i = 0; i < s.length(); i++) { if (s[i] == '(' || s[i] == '{' || s[i] == '[') stack1.push(s[i]); // 如果栈空了,此时的右括号无前面的左括号对应,说明不符合规则 if (s[i] == ')' || s[i] == '}' || s[i] == ']') if (stack1.empty()) return false; if (s[i] == ')') { if (stack1.top() != '(') return false; stack1.pop(); } if (s[i] == '}') { if (stack1.top() != '{') return false; stack1.pop(); } if (s[i] == ']') { if (stack1.top() != '[') return false; stack1.pop(); } } // 如果栈不空,即左括号无对应的有括号,说明字符串不符合规则 if (!stack1.empty()) return false; return true; } };