Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Finding score of brackets in JavaScript
Problem
We are required to write a JavaScript function that takes in a balanced square bracket string, str, as the first and the only argument.
Our function should compute and return the score of the string based on the following rule −
[] has score 1
AB has a score A + B, where A and B are balanced bracket strings.
[A] has score 2 * A, where A is a balanced bracket string.
For example, if the input to the function is
Input
const str = '[][]';
Output
const output = 2;
Example
Following is the code −
const findScore = (str = '') => {
const arr = []
for(const char of str) {
arr.push(char)
while(arr[arr.length - 1] === ']') {
arr.pop()
if(arr[arr.length - 1] === '[') {
arr.pop() arr.push(1)
} else {
let num = arr.pop()
while(arr[arr.length - 1] >= 1) {
num += arr.pop()
}
arr.pop()
arr.push(2 * num)
}
}
}
return arr.reduce((acc, a) => acc + a, 0)
};
console.log(findScore(str));
output
2
Advertisements