Created
November 8, 2013 02:45
-
-
Save ylegall/7365499 to your computer and use it in GitHub Desktop.
run length encode a string
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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