본문 바로가기
LeetCode

[LeetCode] 20. Valid Parentheses

by JungSeung 2023. 10. 24.
728x90

https://leetcode.com/

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

An input string is valid if :
1. Open brackets must be closed by the same type of brackets.
2. Open brackets must be closed in the correct order.
3. Every close bracket has a corresponding open bracket of the same type.


Example 1:

Input: s = "()"
Output: true

 

Example 2:

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

 

Example 3:

Input: s = "(]"
Output: false

 

Constraints:

  • 1 <= s.length <= 10^4
  • s consists of parentheses only '() [] {}'.

 

Code :

var isValid = function(s) {
    // 각 괄호의 매핑을 정의한 객체입니다.
    let map = {
        ")": "(",
        "}": "{",
        "]": "["
    };
    
    // 괄호를 저장할 스택을 초기화합니다.
    let stack = [];
    
    // 문자열을 순회하면서 스택에 push하거나 pop합니다.
    for (let i = 0; i < s.length; i++) {
        if (s[i] === "(" || s[i] === "[" || s[i] === "{") {
            stack.push(s[i]);
        } else if (stack[stack.length - 1] === map[s[i]]) {
            stack.pop();
        } else {
            return false;
        }
    }
    
    // 스택의 길이가 0이면 유효한 괄호 문자열입니다.
    return stack.length ? false : true;
};

 

Solutions Code :

var isValid = function(s) {   
    // 괄호를 저장할 스택을 초기화합니다.
    const stack = [];
    
    // 문자열을 순회하면서 괄호를 처리합니다.
    for (let i = 0 ; i < s.length ; i++) {
        let c = s.charAt(i);
        switch(c) {
            case '(': 
                stack.push(')');
                break;
            case '[': 
                stack.push(']');
                break;
            case '{': 
                stack.push('}');
                break;
            default:
                // 스택에서 팝한 값이 현재 처리중인 값과 다를 경우 유효하지 않은 괄호 문자열입니다.
                if (c !== stack.pop()) {
                    return false;
                }
        }
    }
    
    // 스택의 길이가 0이면 유효한 괄호 문자열입니다.
    return stack.length === 0;
};

 

 

출처 : https://leetcode.com/problemset/all/

 

Problems - LeetCode

Boost your coding interview skills and confidence by practicing real interview questions with LeetCode. Our platform offers a range of essential problems for practice, as well as the latest questions being asked by top-tier companies.

leetcode.com

 

728x90