I've got string interview question regarding run-length-encoding and my solution is O(n). Is there any way to improve it:
const firstString=(str)=>{
const arr = str.split('');
let counter = 1;
let result ='';
for (let i=0; i<arr.length; i++){
if(arr[i] === arr[i+1]){
counter++;
} else {
result +=arr[i]+counter;
counter = 1;
}
} return result
};
firstString('AABBBCAAEE');
Using this approach with regex: Regex to match/group repeating characters in a string
Regex explanation: /((.)\2*)/g
var str = 'AABBBCAAEE';
var result = str.replace(/((.)\2*)/g, function(match) {
var [letter] = match;
return `${letter}${match.length}`;
});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }