Open In App

JavaScript Program to Check Valid Parentheses Using String

In this article, we will learn how we can check valid parentheses of a string, and write a program to check whether the pairs and order of “{ “, ” } “, “(“, “)”, “[“, “]” in the string expression is right or not.

Example:



Input: exp = "[()][()()]()" 
Output: True.
Explanation: all of the brackets are properly formed.
Input: exp = "[(])"
Output: False
Explanation: The first and fourth brackets are not balanced because there is a closing ']' before the final '('.

Using the Stack

This method involves using a stack data structure to keep track of parentheses and ensuring they are properly closed.

Syntax:



stackname.push(value);
stackname.pop()




function isValidParentheses(str) {
    const stack = [];
    const pairs = {
        "(": ")",
        "[": "]",
        "{": "}",
    };
  
    for (let char of str) {
        if (pairs[char]) {
            stack.push(char);
        } else if (
            char === ")" ||
            char === "]" ||
            char === "}"
        ) {
            if (
                pairs[stack.pop()] !==
                char
            ) {
                return false;
            }
        }
    }
  
    return stack.length === 0;
}
  
const inputString = "({()})";
console.log(
    `Is it a valid Paranthesis ? :
${isValidParentheses(inputString)}`
);

Output
Is it a valid Paranthesis ? :
true

Using Counter

This approach relies on using a counter to keep track of the balance between closing parentheses.

Syntax:

for ( variable of iterableObjectName) {
...
}




function isValidParentheses(str) {
    let count = 0;
  
    for (let char of str) {
        if (char === "(") {
            count++;
        } else if (char === ")") {
            if (count === 0) {
                return false;
            }
            count--;
        }
    }
  
    return count === 0;
}
  
const inputString = "((()))";
console.log(
    `Is it a valid Paranthesis ? :
${isValidParentheses(inputString)}`
);

Output
Is it a valid Paranthesis ? :
true

Using Regular Expression

In this method we employ expressions to repeatedly remove valid pairs of parentheses until none remain.

Syntax:

/pattern/modifiers;




function isValidParentheses(str) {
    const regex = /(\(\)|\[\]|\{\})/g;
  
    while (str.match(regex)) {
        str = str.replace(regex, "");
    }
  
    return str.length === 0;
}
  
const inputString = "{[()]]}";
console.log(
    `Is it a valid Paranthesis ?
${isValidParentheses(inputString)}`
);

Output
Is it a valid Paranthesis ?
false

Article Tags :