leetcode-20. 有效的括號
阿新 • • 發佈:2021-07-15
class Solution { public: bool isValid(string s) { int len = s.length(); if(len==0) return true; vector<char> res; if(s[0]==')'||s[0]==']'||s[0]=='}') // 如果第一個元素就是是右括號,返回false return false; stack<char> st; for(int i = 0; i < len; i++){ if(s[i]=='('||s[i]=='['||s[i]=='{'){ // 只要是左括號,直接入棧 //cout<<"s[i]:"<<s[i]<<endl; st.push(s[i]); } else if(s[i]==')'){ // cout<<"s[i]:"<<s[i]<<endl;//cout<<"s[i]:"<<st.top()<<endl; if(st.empty()) // 如果棧為空,又進入一個右括號,無法匹配,返回false; return false; else if(st.top()=='(') // 如果棧不空,進行匹配 st.pop(); else if(st.top()!='(') return false; }else if(s[i]==']'){ if(st.empty()) return false; else if(st.top()=='[') st.pop(); else if(st.top()!='[') return false; }else if(s[i]=='}'){ if(st.empty()) return false; else if(st.top()=='{') st.pop(); else if(st.top()!='{') return false; } } if(st.empty()) // 最後棧為空,返回true return true; else return false; } };