Given a string containing just the characters '('
, ')'
, '{'
, '}'
, '['
and ']'
, determine if the input string is valid.html
An input string is valid if:java
Note that an empty string is also considered valid.git
Example 1:github
Input: "()" Output: true
Example 2:ide
Input: "()[]{}" Output: true
Example 3:post
Input: "(]" Output: false
Example 4:url
Input: "([)]" Output: false
Example 5:spa
Input: "{[]}" Output: true
這道題讓咱們驗證輸入的字符串是否爲括號字符串,包括大括號,中括號和小括號。這裏須要用一個棧,開始遍歷輸入字符串,若是當前字符爲左半邊括號時,則將其壓入棧中,若是遇到右半邊括號時,若此時棧爲空,則直接返回 false,如不爲空,則取出棧頂元素,若爲對應的左半邊括號,則繼續循環,反之返回 false,代碼以下:code
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()) return false; 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(); } };
Github 同步地址:htm
https://github.com/grandyang/leetcode/issues/20
相似題目:
Different Ways to Add Parentheses
Check If Word Is Valid After Substitutions
參考資料:
https://leetcode.com/problems/valid-parentheses/
https://leetcode.com/problems/valid-parentheses/discuss/9178/Short-java-solution