采用栈的结构来检查,遇到左括号则入栈,遇到右括号则对应出栈。如果出栈时没有遇到相应的左括号则表示括号不匹配。如果在最后栈中有元素则表示右括号不足,也表示括号不匹配。
class Solution { public: /** * * @param s string字符串 * @return bool布尔型 */ bool isValid(string s) { // write code here stack<char> char_stack; for(auto& ch: s) { if(ch == '(' || ch=='[' || ch=='{') { char_stack.push(ch); }else if(ch == ')') { //遍历stack; bool flag = false; while(!char_stack.empty()) { char curr = char_stack.top(); if(curr != '(') { char_stack.pop(); }else { char_stack.pop(); flag = true; break; } } if(flag == false) { //没有找到'(',返回false; return false; } } else if(ch == ']') { //遍历stack; bool flag = false; while(!char_stack.empty()) { char curr = char_stack.top(); if(curr != '[') { char_stack.pop(); }else { char_stack.pop(); flag = true; break; } } if(flag == false) { //没有找到'[',返回false; return false; } } else if(ch == '}') { //遍历stack; bool flag = false; while(!char_stack.empty()) { char curr = char_stack.top(); if(curr != '{') { char_stack.pop(); }else { char_stack.pop(); flag = true; break; } } if(flag == false) { //没有找到'{',返回false; return false; } } } return char_stack.empty(); } };