본문 바로가기
코테연습

39.Valid Parentheses

by hxunz 2022. 4. 28.

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

 


function validParentheses(parens) {
  const paren = parens.split('');
  let count = 0;
  
  if (paren[0] === ')' || paren[paren.length-1] === '(' || paren.length%2 === 1) {
    return false;
  }
  
  for (i=0; i < paren.length; i++) {
    if (paren[i] === '(') {
      count += 1;
    } else {
      count -= 1;
    } 
    if (count < 0) {
      return false;
    }
  }
  return count === 0;
}

먼저 문자열에서 글자 하나씩 쪼개서 배열로 만들어줬다.

 

그리고 예외처리를 해주었는데, 배열의 첫번째가 ')' 이거나 배열의 마지막이 '(' 이거나 배열의 길이가 홀수인 경우에는 false를 리턴해주었다.

 

그리고 배열에서 반복문을 돌면서 배열의 요소가 '('인 경우 count에다가 1을 더해주었고 그렇지 않은 경우에는 -1을 해주었다.

 

그리고 count가 0 미만 일때는 false를 리턴했고

 

반복문을 다 돌고 나서 count의 값이 0이면 true를 리턴해주었다.

'코테연습' 카테고리의 다른 글

41. 로또의 최고순위와 최저순위  (0) 2022.05.11
40. 신규 아이디 추천  (0) 2022.05.05
38.Moving Zeros To The End  (0) 2022.04.14
37.Simple Pig Latin  (0) 2022.04.11
36.Does my number look big in this?  (0) 2022.04.10

댓글