문제
https://leetcode.com/problems/valid-parentheses/
1.
function isValid(s: string): boolean {
const map = {
')': '(',
'}': '{',
']': '['
}
const stack = [];
for (let char of s) {
if (char === '(' || char === '{' || char === '[') {
stack.push(char);
} else {
const pop = stack.pop()
const mappp = map[char]
console.log({ pop, mappp })
if (stack.length === 0 || mappp !== pop) {
return false
}
}
}
return stack.length === 0;
};
문제점:
예제 '()[]{}' 가 들어간다고 치면
1. '('
스택에 '(' 가 쌓인다.
stack (
2. ')'
else 구문으로 넘어가서
pop 변수에 값이 할당된다.
stack
그 후 if 조건으로 stack.length === 0 이 만족해버려서 false 라는 잘못된 값이 나온다.
해결책:
조건문에서 비교할 때 pop() 한다.
2.
function isValid(s: string): boolean {
const map = {
')': '(',
'}': '{',
']': '['
}
const stack = [];
for (let char of s) {
if (char === '(' || char === '{' || char === '[') {
stack.push(char);
} else {
const mappp = map[char]
if (stack.length === 0 || mappp !== stack.pop()) {
return false
}
}
}
return stack.length === 0;
};
3. 다른 사람 풀이
function isValid(s: string): boolean {
const stack = [];
const p = { ')': '(', '}': '{', ']': '[' };
for(let i = 0, len = s.length; i < len; i++) {
if (['(', '[', '{'].includes(s[i])) {
stack.push(s[i]);
continue;
}
if (stack.pop() !== p[s[i]]) {
return false;
}
}
return stack.length === 0;
};
'코딩테스트' 카테고리의 다른 글
[LeetCode/TS] 13. Roman to Integer (0) | 2024.12.27 |
---|---|
[Leetcode/TS] 9. Palindrome Number (1) | 2024.12.19 |
[Leetcode/TS] 2. Add Tow Number (0) | 2024.12.18 |
[Leetcode/TS] 1. Two Sum (1) | 2024.12.17 |
프로그래머스 | 레벨0 | Kotlin (0) | 2024.02.02 |