Run Code
|
API
|
Code Wall
|
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
//Rhino 1.7.7.1print("Hello, world!")
not worked!!
ComposeWordsGrid
Time it has been since Tuesday, January 1st, 2019
LearningJavaScript
JS is_sorted
Nth Fibonacci Number
1
Arrays
empty