How to use Counter In Javascript
This approach relies on using a counter to keep track of the balance between closing parentheses.
- Start by initializing a counter variable.
- Iterate through each character in the given string.
- Increment the counter whenever an open parenthesis is encountered and decrement it for each closing parenthesis found.
- If at any point during iteration the counter becomes negative it implies that there are closing parentheses than opening ones; thus return false.
- Once finished iterating through all characters in the string if the counter equals zero it indicates that all parentheses have been properly balanced, hence return true.
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
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