괄호가 입력되면 올바른 괄호이면 “YES", 올바르지 않으면 ”NO"를 출력합니다.
(())() 이것은 괄호의 쌍이 올바르게 위치하는 거지만, (()()))은 올바른 괄호가 아니다.
첫 번째 줄에 괄호 문자열이 입력됩니다. 문자열의 최대 길이는 30이다.
첫 번째 줄에 YES, NO를 출력한다.
입력
(()(()))(()
출력
NO
// 스택 구조를 이용해서 푼 거
const solution = (str) => {
const stack = [];
for (let x of str) {
x === "(" ? stack.push(x) : stack.pop();
}
return stack.length === 0 ? "YES" : "NO";
};
const answer = solution("(()(()))(()");
const wrong = solution("(())()");
console.log(answer, wrong); // NO YES
// 비슷하지만 다르게 푼 거
const solution = (str) => {
let cal = 0;
for (let x of str) {
x === "(" ? (cal = cal + 1) : (cal = cal - 1);
}
return cal === 0 ? "YES" : "NO";
};
const answer = solution("(()(()))(()");
const wrong = solution("(())()");
console.log(answer, wrong); // NO YES