Skip to content

Instantly share code, notes, and snippets.

@ylegall
Created November 8, 2013 02:45
Show Gist options
  • Save ylegall/7365499 to your computer and use it in GitHub Desktop.
Save ylegall/7365499 to your computer and use it in GitHub Desktop.
run length encode a string
import java.util.*;
public class Test
{
static String rle(String input) {
if (input == null || input.equals("")) return "";
StringBuilder sb = new StringBuilder();
int i = 0;
while (i < input.length()) {
int j = 1;
while (i + j < input.length() && input.charAt(i) == input.charAt(i+j)) ++j;
sb.append(input.charAt(i)).append(j);
i += j;
}
return sb.toString();
}
public static void main(String[] args) {
System.out.println(rle("aabbaadddc")); // a2b2a2d3c1
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment