[LeetCode] Valid Parentheses

1.Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

2.題目要求:判斷給出的string中,括號是不是一一對應(yīng)的,比如 ( ) 或者 { } [ ] ( )算合法的括號,(] 或者 ( [ ) ] 都不合法。

3.方法:用一個Stack來存儲括號, 遍歷傳入的string,如果遇到左括號就入棧;如果遇到右括號,檢查棧如果為空,證明不能匹配,如果棧不空,pop出棧頂?shù)脑?,看是否與當(dāng)前的右括號匹配。如果匹配,繼續(xù)向下進(jìn)行新一輪的循環(huán),如果不匹配,返回false。

4.代碼:
class Solution {
public:
bool isValid(string s) {
stack<char> paren;
for (char& c : s) {
switch (c) {
case '(':
case '{':
case '[': paren.push(c); break;
case ')': if (paren.empty() || paren.top()!='(') return false; else paren.pop(); break;
case '}': if (paren.empty() || paren.top()!='{') return false; else paren.pop(); break;
case ']': if (paren.empty() || paren.top()!='[') return false; else paren.pop(); break;
default: ; // pass
}
}
return paren.empty() ;
}
};

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容