풀이
닫힘괄호(), }, ])가 들어왔을 때, stack에 마지막으로 들어있는 값을 확인한다. 마지막 값이 pair((, {, [)이면 pop한다. 아닌 경우는 모두 push한다. stack에 남은 원소 값이 있는 경우 NO를 반환한다.
function isBalanced(s) {
// Write your code here
const array = s.split("");
let stack = [];
for (let item of array) {
if (item === "{" || item === "[" || item === "(") {
stack.push(item);
} else {
// console.log(item, stack[stack.length - 1]);
if (stack.length === 0) {
return "NO";
}
if (item === "}" && stack[stack.length - 1] === "{") {
stack.pop();
} else if (item === "]" && stack[stack.length - 1] === "[") {
stack.pop();
} else if (item === ")" && stack[stack.length - 1] === "(") {
stack.pop();
} else {
stack.push(item);
}
}
}
return stack.length > 0 ? "NO" : "YES";
}
'Programming > 데일리 알고리즘' 카테고리의 다른 글
(210519:BTB) Lesson 6. MaxProductOfThree (0) | 2021.05.19 |
---|---|
(210519:BTB) Lesson 6. Distinct (0) | 2021.05.19 |
[HackerRank] Sherlock and the Valid String (Javascript) (0) | 2021.05.15 |
(210502:BTB) Lesson 5. CountDiv (0) | 2021.05.02 |
(210502:BTB) Lesson 5. PassingCar (0) | 2021.05.02 |