-
leeCode - Valid Parentheses프로그래밍/algorithm 2021. 7. 26. 10:30
문제
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.
Example 1:
Input: s = "()" Output: true
Example 2:
Input: s = "()[]{}" Output: true
Example 3:
Input: s = "(]" Output: false
Example 4:
Input: s = "([)]" Output: false
Example 5:
Input: s = "{[]}" Output: true
Constraints:
- 1 <= s.length <= 104
- s consists of parentheses only '()[]{}'.
풀이
const isValid = function (s) { let stack = []; const comp = { '(': ')', '{': '}', '[': ']' }; for (let i = 0; i < s.length; i++) { if (comp[s[i]]) { stack.push(s[i]); } else { if (!stack.length) return false; if (comp[stack.pop()] !== s[i]) return false; } } return stack.length ? false : true };
'프로그래밍 > algorithm' 카테고리의 다른 글
leetCode - Generate Parentheses (0) 2021.07.26 leetCode - Merge Two Sorted Lists (0) 2021.07.26 leetCode - Remove Nth Node From End of List (0) 2021.07.26 leetCode-4Sum(two pointer) (0) 2021.07.22 leetCode - Letter Combinations of a Phone Number(backtracking) (0) 2021.07.22