Tech Qu: Write a function to do RLE (Run Length Encoding)
- Given a string, compress using run-length encoding. Example:
Input: aaabbac
Output: a3b2ac
First Pass – simplistic solution
Code Snippet
- /// <summary>
- /// Assuming no digits in string.
- /// </summary>
- /// <param name="s"></param>
- /// <returns></returns>
- public static string RLEEncode1(string s)
- {
- var sb = new StringBuilder();
- int count = 1;
- char current = s[0];
- for (int i = 1; i < s.Length; i++)
- {
- if (current == s[i])
- {
- count++;
- }
- else
- {
- if (count > 1)
- sb.AppendFormat("{1}{0}", count, current);
- else
- sb.Append(current);
- count = 1;
- current = s[i];
- }
- }
- if (count > 1)
- sb.AppendFormat("{1}{0}", count, current);
- else
- sb.Append(current);
- return sb.ToString();
- }
A better solution is to assume that there are no characters > 127 in the string and using the range 128-255 as counter indicators. This solution is shown below.
Code Snippet
- public static string RLEEncode2(string s)
- {
- var sb = new StringBuilder();
- int count = 1;
- char current = s[0];
- for (int i = 1; i < s.Length; i++)
- {
- if (current == s[i])
- {
- count++;
- if(count > 127)
- {
- sb.Append(current);
- sb.Append((char)(count + 127));
- count = 1;
- }
- }
- else
- {
- if (count > 1)
- {
- sb.Append(current);
- sb.Append((char)(count + 127));
- }
- else
- sb.Append(current);
- count = 1;
- current = s[i];
- }
- }
- if (count > 1)
- {
- {
- sb.Append(current);
- sb.Append((char)(count+127));
- }
- }
- else
- sb.Append(current);
- return sb.ToString();
- }
Inspecting the string, we see the result:
[0] 97 'a' char
[1] 130 '' char
[2] 98 'b' char
[3] 129 '' char
[4] 97 'a' char
[5] 99 'c' char
Comments
Post a Comment