AB3 有效括号序列
链接:有效括号序列_牛客题霸_牛客网
题解:
利用栈,左括号入栈,右括号就取出栈顶元素看是否和右括号匹配,不匹配则false
#include <stack>
class Solution {
public:/*** 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可** * @param s string字符串 * @return bool布尔型*/bool Judge(char c1,char c2){if(c1=='('&&c2==')') return true;if(c1=='['&&c2==']') return true;if(c1=='{'&&c2=='}') return true;return false;}bool isValid(string s) {// write code herestd::stack<char> st;for(int i=0;i<s.size();i++){if(s[i]=='('||s[i]=='['||s[i]=='{')//左括号{st.push(s[i]);}else//右括号{if(st.empty()) return false;else{char c=st.top();if(!Judge(c,s[i])) return false;else st.pop();}}}if(st.empty()) return true;else return false;}
};