Categories
Leetcode Parenthesis Recursion String

Decode String

let decodeString = function(str) {

if (str.indexOf("[") < 0) {
return str;
}

let openingIndex = [];
let newStr = "";
for (let i = 0; i < str.length; i++) {
if (str[i] === "[") {
openingIndex.push(i);
newStr += str[i];
}
else if (str[i] === "]") {
let opening = openingIndex.pop();
let allMultipliers = str.substring(0, opening).match(/\d+/g);
let multiplier = allMultipliers[allMultipliers.length - 1];
let data = str.substring(opening + 1, i);
if (data.indexOf("[") < 0) {
newStr = newStr.substring(0, newStr.lastIndexOf("[") - multiplier.length) + data.repeat(multiplier);
console.log({opening, multiplier, data, newStr});
}
else {
newStr += str[i];
}
}
else {
newStr += str[i];
}
}

return decodeString(newStr);
};
Categories
Leetcode Parenthesis String

Valid Parenthesis

function validParenthesis(str) {

let closingMap = {
')' : '(',
']' : '[',
'}' : '{'
}

let chars = [];
for(let i = 0; i < str.length; i++) {
if (str[i] === '(' || str[i] === '[' || str[i] === '{') {
chars.push(str[i]);
}
else {
let compare = chars.pop();
if (closingMap[str[i]] !== compare) return false;
}
}
return chars.length === 0;
}