THE PROBLEM STATEMENT
Implement a method to perform basic string decompression using the counts of repeated characters. For example, the string “a2bd3” would become “aabddd”.
Also do you think you could perform any optimization to your algorithm. hint: use cache
Example 1
Input: string = “a2b2c2”Output: “aabbcc”
Example 2
Input: string = “a3bc4d10”Output: “aaabccccdddddddddd”
Example 3
Input: string = “a0b0c0dd”Output: “dd”
Explanation:
Add the functionality that if a string character has 0 next then remove that character. Though this is not going to occur as compression won’t work like that.
SOLUTION?
So before you see my solution below I recommend you to try solving it yourself first.
Scroll Down For Solution…
SOLUTION
function decodeString(str) { if (str == null || str.length == 0) throw new Error('String should not be null or empty.'); if (!isNaN(str[0])) throw new Error('First character should be a letter.'); let retStr = ''; for (let i = 0; i < str.length; i++) { if (i == str.length - 1 || isNaN(str[i + 1])) { retStr += str[i]; } else { let j = i + 1; let numberStr = ''; while (!isNaN(str[j])) { numberStr += str[j]; j++; } if (Number(numberStr) != 0) { for (let k = 0; k < Number(numberStr); k++) { retStr += str[i]; } } i = j - 1; } } return retStr; } console.log(decodeString("abcd")); // abcd console.log(decodeString("a2b2c2d2")) // aabbccdd console.log(decodeString("a2b0c1d3")) // aacddd console.log(decodeString("A10")) // AAAAAAAAAA
Please comment if you have anything in mind.
Thanks for stopping by! Happy coding!
Excellent
Thank you!
Thanks sir its very use full
you’re welcome 🙂
Hi 🙂
Here’s my solution
function decodeString(str) {
let res = ”;
const letters = str.split(/[0-9]+/).join(”).split(”);
letters.forEach(v => {
if (str.match(new RegExp(`${v}[0-9]+`))) {
res += v.repeat(str.match(new RegExp(`${v}[0-9]+`))[0].split(v)[1]);
} else {
res += v;
}
})
return res;
}
console.log(decodeString(‘a2b2c2’));
console.log(decodeString(‘a3bc4d10’));
console.log(decodeString(‘a0b0c0dd’));
https://gist.github.com/shiv19/b066adfa5b9a1c2b123c55af1acca650
Hi Shiva, it fails in few cases e.g. “a1a3b2c2”. If a letter repeats, this line will bring the first searched string “if (str.match(new RegExp(`${v}[0-9]+`)))” So you need to track the integer as well with string. But nice approach though!
Thanks a bunch! This a terrific webpage!
Keep up the exceptional work !! Lovin’ it!
Thank you!