CodeWars 코딩 문제 2021/04/15 - Valid Parentheses

이호현·2021년 4월 15일
0

Algorithm

목록 보기
101/138

[문제]

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, 아니면 falsereturn.

[풀이]

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;
}

괄호가 담긴 문자열을 처음부터 순회하면서 (일 때는 배열에 넣고, )일 때는 배열의 마지막 요소에 따라 짝을 맞출건지 falsereturn할 건지 조건을 걸어서 반복문을 돌림.

마지막에 배열에 요소가 있으면 짝이 다 안맞은 거니 falsereturn하고, 요소가 없으면 짝이 다 맞은거니 truereturn.

profile
평생 개발자로 살고싶습니다

0개의 댓글