How to use a Map for Character Matching In Javascript
This method uses a stack and a Map to match opening and closing brackets. As characters are processed, opening brackets are pushed onto the stack. When a closing bracket is encountered, it is checked against the stack’s top. The string is valid if the stack is empty.
Example: In this example The function isValidParentheses checks if a given string of parentheses is valid. It utilizes a stack and a map to match opening and closing parentheses. The examples demonstrate its correctness.
function isValidParentheses(s) {
const stack = [];
const matchingBrackets = new Map([
['(', ')'],
['{', '}'],
['[', ']']
]);
for (let char of s) {
if (matchingBrackets.has(char)) {
stack.push(char);
} else {
if (stack.length === 0 || matchingBrackets.get(stack.pop()) !== char) {
return false;
}
}
}
return stack.length === 0;
}
console.log(isValidParentheses("(){}[]"));
console.log(isValidParentheses("([{}])"));
console.log(isValidParentheses("(]"));
Output
true true false
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