Oracle | Phone Screen | Run-length Encoding

Difficulty: MEDIUMCategory: InterviewExperienceFrequency: 1Asked On 2017-11-07Added By Anonymous
Source: Link

Company: Oracle
Role: unknown
Interview Stage: Phone Screen
Location: unknown
Year: unknown

Original Post Content:

Below question asked during Oracle Phone screening, thought to share.

Given a string, output the run length encoding of that string so that repeat letters are compressed to the character and count.
Example:
abcccddeeeeea => abc3d2e5a

string CompressString(string str)
{

  if (str.Length < 2)
  {
    return str;
  }
  StringBuilder output = new StringBuilder();
  int count =1;
  for (int i=0 ; i < str.Length; i++ )
  {
     if (i+1 < str.Length && str[i] == str[i+1] )
     {
         count++;
         i++;
        }
     
       if (count > 1)
       {
        output.Append(count);
        count =1;
       } 
         i++;
     }
     
    
     return output.ToString();
  }

}
Comments