判断一串括号是否有效。
栈的经典用法。
class Solution {
public:
bool isValid(string s) {
stack<char> st;
int len=s.length();
for(int i=0;i<len;i++){
if(s[i]==']'||s[i]==')'||s[i]=='}'){
if(st.empty()) return false;
if((s[i]==']'&&st.top()=='[')||(s[i]==')'&&st.top()=='(')||(s[i]=='}'&&st.top()=='{')) st.pop();
else return false;
}
else st.push(s[i]);
}
if(!st.empty()) return false;
return true;
}
};