Write a function StringChallenge(str)
that takes a string as input and returns a compressed version of the string using the Run-length encoding algorithm. This algorithm counts the occurrences of each repeating character and outputs the count followed by that character.
Input:
"aabbcde"
Output:2a2b1c1d1e
Input:
"wwwbbbw"
Output:3w3b1w
The string will not contain any numbers, punctuation, or symbols.
public class StringChallenge {
// Function to perform Run-Length Encoding on the input string
public static String runLengthEncode(String str) {
StringBuilder encoded = new StringBuilder();
int n = str.length();
for (int i = 0; i < n; i++) {
int count = 1;
// Count occurrences of the current character
while (i + 1 < n && str.charAt(i) == str.charAt(i + 1)) {
count++;
i++;
}
// Append the count and character to the result
encoded.append(count).append(str.charAt(i));
}
return encoded.toString();
}
public static void main(String[] args) {
// Test cases
System.out.println(runLengthEncode("aabbcde")); // Expected Output: 2a2b1c1d1e
System.out.println(runLengthEncode("wwwbbbw")); // Expected Output: 3w3b1w
System.out.println(runLengthEncode("abcccc")); // Expected Output: 1a1b4c
System.out.println(runLengthEncode("ggggoppppp")); // Expected Output: 4g1o5p
}
}
// Function to perform Run-Length Encoding using LinkedHashMap
public static String runLengthEncode(String str) {
// Use LinkedHashMap to maintain the order of characters
LinkedHashMap charCountMap = new LinkedHashMap<>();
StringBuilder encoded = new StringBuilder();
// Traverse the string and populate the LinkedHashMap
for (char ch : str.toCharArray()) {
charCountMap.put(ch, charCountMap.getOrDefault(ch, 0) + 1);
}
// Build the encoded string from the LinkedHashMap
for (Map.Entry entry : charCountMap.entrySet()) {
encoded.append(entry.getValue()).append(entry.getKey());
}
return encoded.toString();
}