JS 코딩테스트 문제풀이(Valid parentheses)

Minji Lee·2023년 9월 5일
0

JS코딩테스트

목록 보기
9/122
post-thumbnail

Valid parentheses

Valid parentheses

문제

Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

An input string is valid if:

Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Every close bracket has a corresponding open bracket of the same type.

코드

var isValid = function(s) {
    let result;
    let stack=[]; // 스택 배열 생성
    for(let i=0; i<s.length;i++){
        if(s[i]==='('){
            stack.push(')');
        }else if(s[i]==='['){
            stack.push(']');
        }else if(s[i]==='{'){
            stack.push('}');
        }else if(stack.length > 0 && s[i]===stack[stack.length-1]){
            stack.pop();
        }else{
            result=false;
            break;
        }
        result=true;
    }
    if(result && stack.length) result=false; 
  // true로 리턴되었는데 stack이 남아있는 경우 false반환 -> ex) {
    return result;
};

풀이 및 해설

  • () {} [] 이런식으로 짝이 맞아야함
  • 스택 이용 → 여는 괄호는 스택에 닫는 괄호를 push를 해주고, 닫는 괄호일 경우 top에 있는 것과 일치하면 pop하도록

0개의 댓글