Search code examples
javascriptstringalgorithmencodingrun-length-encoding

improve run-length-encoding algorithm


I've got string interview question regarding run-length-encoding and my solution is O(n). Is there any way to improve it:

  • input is AABBBCAAEE
  • output suppose to be A2B3C1A2E2

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');


Solution

  • Using this approach with regex: Regex to match/group repeating characters in a string

    Regex explanation: /((.)\2*)/g

    enter image description here

    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; }