[알고리즘] LeetCode - Valid Parentheses

Jerry·2021년 1월 16일
0

LeetCode

목록 보기
14/73
post-thumbnail

LeetCode - Valid Parentheses [난이도:Easy]

문제 설명

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.

입출력 예시

Example 1:
Input: s = "()"
Output: true

Example 2:
Input: s = "()[]{}"
Output: true

Example 3:
Input: s = "(]"
Output: false

Example 4:
Input: s = "([)]"
Output: false

Example 5:
Input: s = "{[]}"
Output: true

제약사항

1 <= s.length <= 104
s consists of parentheses only '()[]{}'.

Solution

let isValid = function(s) {
    let array=[];

    for(let val of s){
        if(val=='('||val=='{'||val=='['){ // 여는 괄호는 push
            array.push(val);
        }
        else{
            let popVal=array.pop(); // 닫는 괄호인 경우 pop 해서 유효성 검증

            if(val==')'){ 
                if(popVal!='('){
                    return false;
                }
            }
            else if(val==']'){
                if(popVal!='['){
                    return false;
                }
            }
            else if(val=='}'){
                if(popVal!='{'){
                    return false;
                }
            }
        } 
    }

    if(array.length>0){
        return false;
    }
    return true;
};

즐건 주말 ^~^

profile
제리하이웨이

0개의 댓글