[LeetCode] Valid Parentheses 驗證括號
阿新 • • 發佈:2018-12-27
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,如不為空,則取出棧頂元素,若為對應的左半邊括號,則繼續迴圈,反之返回false,程式碼如下:
class Solution { public: bool isValid(string s) { stack<char> parentheses; for (int i = 0; i < s.size(); ++i) { if (s[i] == '(' || s[i] == '[' || s[i] == '{') parentheses.push(s[i]); else { if (parentheses.empty()) returnfalse; if (s[i] == ')' && parentheses.top() != '(') return false; if (s[i] == ']' && parentheses.top() != '[') return false; if (s[i] == '}' && parentheses.top() != '{') return false; parentheses.pop(); } }return parentheses.empty(); } };
類似題目:
參考資料: