20. Valid Parentheses Leetcode solution in JavaSctipt (js)

0

Table of Contents

Problem

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 <= 104
  • s consists of parentheses only '()[]{}'.

Solution

/**
 * @param {string} s
 * @return {boolean}
 */
var isValid = function(s) {
    let opentags = new Array();
    for(let i = 0; i<s.length;i++){
        if(i == 0 && (s[i] == "]" || s[i] == "}" || s[i] == ")")){
            return false;
        }
        switch(s[i])
        {
            case "]":
            let lastElem = opentags.pop();
            if(lastElem != "["){
                return false;
            }
            break;
            case "}":
            let lastElema = opentags.pop();
            if(lastElema != "{"){
                return false;
            }
            break;
            case ")":
            let lastElemb = opentags.pop();
            if(lastElemb != "("){
                return false;
            }
            break;
            default:
            opentags.push(s[i]);
            break;
        } 

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

Leave a Comment

Skip to content