Write a function that takes a string of parentheses, and determines if the order of the parentheses is valid. The function should return true if the string is valid, and false if it's invalid.
Examples
"()" => true
")(()))" => false
"(" => false
"(())((()())())" => true
Constraints
0 <= input.length <= 100
(요약) 괄호가 열고 닫는게 제대로 짝이 맞으면 true
, 아니면 false
를 return
.
function validParentheses(parens){ const stack = []; for(let i = 0; i < parens.length; i++) { if(parens[i] === ')' && stack[stack.length - 1] === '(') { stack.pop(); } else if(parens[i] === '(') { stack.push('('); } else { return false; } } return stack.length ? false : true; }
괄호가 담긴 문자열을 처음부터 순회하면서
(
일 때는 배열에 넣고,)
일 때는 배열의 마지막 요소에 따라 짝을 맞출건지false
를return
할 건지 조건을 걸어서 반복문을 돌림.마지막에 배열에 요소가 있으면 짝이 다 안맞은 거니
false
를return
하고, 요소가 없으면 짝이 다 맞은거니true
를return
.