You are viewing a single comment's thread. Return to all comments →
Hi everyone, here's my code in js. Let me know how I can improve it. Thanks
function stringCompression(str) { let idx = 0, strLen = str.length, result = ""; while (idx < strLen && str[idx] !== null) { const currChar = str[idx]; let ctr = 1; idx++; while (currChar === str[idx]) { ctr++; idx++; } result += `${currChar}${ctr > 1 ? ctr : ""}`; } return result.length < str.length ? result : str; }
i/p:
console.log(stringCompression("aabcccccaaa")); console.log(stringCompression("abcd")); console.log(stringCompression("aaabaaaaccaaaaba"));
o/p:
a2bc5a3 abcd a3ba4c2a4ba
Seems like cookies are disabled on this browser, please enable them to open this website
String Compression
You are viewing a single comment's thread. Return to all comments →
Hi everyone, here's my code in js. Let me know how I can improve it. Thanks
Test case:
i/p:
o/p: