How to use the Stack In Javascript
This method involves using a stack data structure to keep track of parentheses and ensuring they are properly closed.
- Begin by initializing a stack.
- Iterate, through the given string.
- If an open parenthesis is encountered, push it onto the stack.
- If a closing parenthesis is encountered check if it matches the element of the stack.
- If they match, pop the element from the stack; otherwise conclude that the parentheses are not balanced and return false.
- After iterating through all characters in the string if the stack is empty it means all parentheses have been correctly closed so return true.
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
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 '('.
Table of Content
- Using the Stack
- Using Counter
- Using Regular Expression
- Using a Map for Character Matching
- Using a recursive function:
Contact Us