We need to write a JavaScript function that accepts a balanced square bracket string str as the first and only parameter.
Our function should calculate and return the score of the string according to the following rules -
[] has a score of 1
[A] has a score of 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;
The 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));
2
The above is the detailed content of Find bracket fractions in JavaScript. For more information, please follow other related articles on the PHP Chinese website!