This file contains 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.*; | |
class Program { | |
// O(n) T | O(n) S | |
public String runLengthEncoding(String string) { | |
// handle corner cases | |
if (string == null || string.length() == 0) { | |
return string; | |
} | |
int currentRunLength = 1; | |
StringBuilder encodedStringCharacters = new StringBuilder(); | |
for (int i = 1; i < string.length(); i++) { | |
char previousChar = string.charAt(i - 1); | |
char currentChar = string.charAt(i); | |
if ((currentChar != previousChar) || (currentRunLength == 9)) { | |
encodedStringCharacters.append(currentRunLength); | |
encodedStringCharacters.append(previousChar); | |
currentRunLength = 1; | |
} else { | |
currentRunLength++; | |
} | |
} | |
// handle the last run | |
if (currentRunLength > 0) { | |
encodedStringCharacters.append(currentRunLength); | |
encodedStringCharacters.append(string.charAt(string.length() - 1)); | |
} | |
return encodedStringCharacters.toString(); | |
} | |
} |
No comments:
Post a Comment