var isValid = function(s) {
//1. 매칭될 괄호를 선언한다
const map = {
'(' : ')',
'{' : '}',
'[' : ']'
};
//2. 열린괄호만 따로 모아준다
const open = Object.keys(map);
//3. 결과값과 stack을 선언
let answer = true;
const stack = [];
//4. 짝수가 아닌 것들은 걸러낸다
if (s.length % 2 !== 0) return false;
for (let x of s) {
// 스택에 열린 괄호를 넣는다
if(open.includes(x)){
stack.push(x);
}
// 닫힌 괄호인 경우
else {
// stack의 마지막 열린 괄호의 value와 x가 같다면 (왜 꼭 마지막 괄호지..?)
if (map[stack[stack.length - 1]] === x){
stack.pop();
}
else{
return false;
}
}
}
//stack이 짝수일때 return false조건을 추가해줬다...
if(stack.length > 0) return false
return answer;
};
출처: https://leetcode.com/problems/valid-parentheses/submissions/
출처: https://www.youtube.com/watch?v=IhJGJG-9Dx8