解題思路:
(1)利用棧的先進後出原則,先匹配後進入的右括號
(2)遇到( [ {,進棧
(3)遇到 )] },和棧頂的元素比較是否匹配,匹配則棧頂元素出棧
(4)全部匹配,最後棧的大小爲空
class Solution {
public:
bool isValid(string s) {
stack<char> st;
char top;
for (int i=0;i<s.length();i++) {
if (s[i]=='('||s[i]=='['||s[i]=='{') st.push(s[i]);
else if (st.empty()) return false;
else {
top = st.top();
if (top=='('&&s[i]!=')') return false;
else if (top=='['&&s[i]!=']') return false;
else if (top=='{'&&s[i]!='}') return false;
else st.pop();
}
}
return true;
}
};