Algorithm


Problem Name: 20. Valid Parentheses

Problem URL: https://leetcode.com/problems/valid-parentheses/

Level: Easy

Details:

We'll use Stack Data structure to solve this Leetcode Valid Parentheses problem

Details:

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 '()[]{}'.

Code Examples

#1 Code Example with Javascript Programming

Code - Javascript Programming


/**
 * Is Valid Parenthesis
 *
 * @param {string} s
 * @return {boolean}
 */
var isValid = function(s) {
    const parenthesis = {
        '(' : ')',
        '{' : '}',
        '[' : ']',
    };
    
    const stack = [];
    for(let i = 0; i < s.length; i++) {
    	const charParen = s[i];
    
        if (Object.keys(parenthesis).includes(charParen)) {
        	stack.push(charParen)
        } else {
        	const startParen = Object.keys(parenthesis).find(key => parenthesis[key] === charParen); 
        	if (stack?.[stack.length - 1] === undefined) {
            	return false;
            }
        
            if (stack?.[stack.length - 1] === startParen) {
        		stack.pop();
        	} else {
            	return false;
            }
        }
    }
    
    if (stack.length === 0) {
    	return true;
    }
    
    return false;
};
Copy The Code & Try With Live Editor

Input

x
+
cmd
()[]{}

Output

x
+
cmd
true

Demonstration


Leetcode - 20. Valid Parentheses solution in Javascript