I'm having slight trouble trying to compress a string using recursion.
For example, consider the following string:
qwwwwwwwwweeeeerrtyyyyyqqqqwEErTTT
After applying the RLE algorithm, this string is converted into:
q9w5e2rt5y4qw2Er3T
In the compressed string, "9w" represents a sequence of 9 consecutive lowercase "w" characters. "5e" represents 5 consecutive lowercase "e" characters, etc.
I already have a code for compressing it without recursion:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Compress {
public static String input(String source) {
StringBuffer coding = new StringBuffer();
for (int i = 0; i < source.length(); i++) {
int runLength = 1;
while (i+1 < source.length() && source.charAt(i) == source.charAt(i+1)) {
runLength++;
i++;
}
if (runLength>1){
coding.append(runLength);
}
coding.append(source.charAt(i));
}
return coding.toString();
}
public static void main(String[] args) {
IO.outputStringAnswer("Enter a string");
String str = IO.readString();
String result = "";
result=input(str); //function(variable)
IO.outputStringAnswer(result);
}
}
But I am unsure if this is able to be turned into a recursion version of this.