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() ;
}
};