0. 문제
https://leetcode.com/problems/valid-parentheses/
Valid Parentheses - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
주어진 문자열에서 에서 괄호가 순서대로 닫혔는지 여부를 확인하여 반환하는 문제
#1
Input: s = "()"
Output: true
#2
Input: s = "()[]{}"
Output: true
#3
Input: s = "(]"
Output: false
1.언어
자바스크립트(JavaScript)
2. 문제 풀이
var isValid = function(s) {
const map= {
'(':')',
'{':'}',
'[':']',
};
let arr=Array(s.length), count=0;
for (let i of s){
if (i in map){
arr[count++] = map[i]; // 닫는 괄호 넣기
} else{
if (arr[count-1] != i) return false
count--;
arr[count]=0;
}
}
if (count == 0) return true
return false
};
Runtime: 88 ms, faster than 56.28% of JavaScript online submissions for Valid Parentheses.
Memory Usage: 42.1 MB, less than 75.99% of JavaScript online submissions for Valid Parentheses.
문자열을 읽으며 여는 괄호[key]는 배열에 값[vlaue]을 추가하고 닫는 괄호[vlaue]를 만나면 배열 중 가장 최근에 추가한 값과 비교해 판별한다.
'LeetCode > 코딩 테스트 스터디 2주차' 카테고리의 다른 글
[LeetCode] 6. Zigzag Conversion 풀이 (JS) (0) | 2022.07.17 |
---|---|
[LeetCode] 27. Remove Element 풀이 (JS) (0) | 2022.07.17 |
[LeetCode] 26. Remove Duplicates from Sorted Array 풀이 (JS) (0) | 2022.07.17 |
[LeetCode] 5. Longest Palindromic Substring 풀이 (JS) (0) | 2022.07.17 |
[LeetCode] 21. Merge Two Sorted Lists 풀이 (JS) (0) | 2022.07.17 |