Run Code
|
API
|
Code Wall
|
Users
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
strCompression
//JavaScript-C24.2.0 (SpiderMonkey) print(strCompression('aaabbbcccccaa')); print(strCompression2('aaabbbcccccaa')); // string compression algo // aaabbbcccccaa -> a3b3c4a2 function strCompression(str) { if (str.length == 0) return ''; let newStr = ''; let count = 0; let prevChar = str[0]; for (let i = 0; i < str.length; i++) { if (str[i] !== prevChar) { newStr += str[i-1] + count; prevChar = str[i]; count = 0; } count++; if (i === str.length-1) { newStr += str[i] + count; } } return newStr; } // to simulate a string buffer, build an array of characters and do a join function strCompression2(str) { if (str.length == 0) return ''; let newStr = []; let count = 0; let prevChar = str[0]; for (let i = 0; i < str.length; i++) { if (str[i] !== prevChar) { newStr.push(str[i-1] + count); prevChar = str[i]; count = 0; } count++; if (i === str.length-1) { newStr.push(str[i] + count); } } return newStr.join(''); }
run
|
edit
|
history
|
help
0
Please
log in
to post a comment.
SetofStacks
TaskhelTemplate
100034322376708
Strange Attractors
2-D Kinematics with accurate air drag
nuBuilder - Calc precision
Tik
containsPalindrome
I love sorting
More JS
Please log in to post a comment.