keep learning, keep coding!
Problem - Valid Parentheses
Given a string s containing just the characters (
, )
, {
, }
, [
and ]
, determine if the input string is valid.
An input string is valid if:
- Open brackets must be closed by the same type of brackets.
- Open brackets must be closed in the correct order.
- Every close bracket has a corresponding open bracket of the same type.
翻譯蒟蒻
每個開放的括號,必須有一個相應的關閉括號,並且必須按照正確的順序配對。
Example 1:
1
2Input: s = "()"
Output: trueExample 2:
1
2Input: s = "()[]{}"
Output: trueExample 3:
1
2Input: s = "(]"
Output: false
定義一個 map 作為對照。
每當遇到左括號,就將其推入 stack 堆疊;每當遇到右括號,就從 stack 堆疊中彈出一個元素,並檢查彈出的元素是否與當前的右括號匹配。如果在任何時候都不匹配,則返回false
。如果遍歷完所有後 stack 堆疊為空,則返回true
。
Solution - JavaScript
1 | var isValid = function(s) { |
Solution - Ruby
1 | def is_valid(s) |
Solution - PHP
1 | function isValid($s) { |