LeetCode 20 Valid Parentheses(用棧判斷括號匹配)
阿新 • • 發佈:2019-01-02
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.
題目大意:給出一個包含三種括號的序列,判斷括號是否匹配。
解題思路:用一個棧儲存未匹配的左括號,然後遍歷字串,判斷當前字元是左括號還是右括號。如果當前字元是左括號,那麼將其入棧;如果當前字元是右括號且棧非空,那麼判斷是否與棧頂的左括號相匹配,如果匹配則彈出棧頂元素,不匹配則返回false。最後判斷棧是否為空。
程式碼如下:
class Solution { public: bool isValid(string s) { stack<char> stk; int len = s.length(); for(int i = 0;i < len;i++){ if(s[i] == '{' || s[i] == '[' || s[i] == '(') { stk.push(s[i]); } else if(stk.size() && isPair(stk.top(), s[i])){ stk.pop(); } else { return false; } } return stk.empty(); } private: bool isPair(char x, char y) { if( (x == '{' && y == '}') || (x == '[' && y == ']') || (x == '(' && y == ')') ){ return true; } else return false; } };