Open knasim opened 5 years ago
The following does not work in all cases. so solution has to be better than this:
`
StringBuilder compressed = new StringBuilder();
int len = input.length();
for(int i=0; i < len; i++) {
int counter = 1;
while(i < len-1 && input.charAt(i) == input.charAt(i+1)) {
i++;
counter++;
}
compressed.append(counter);
compressed.append(input.charAt(i));
}
return compressed.toString();
`
The solution that is immediately obvious to me is to only append the counter variable to the string if counter > 1 (there was a run).
if(counter > 1) compressed.append(counter);
compressed.append(input.charAt(i));
If there are no runs in a string, the output will simply be the input string.
Without much context, I'm not sure if this fits the criteria of the problem, because it's not truly RLE, but it is a potential solution.
Uber:
Classic run length encoding problem. Given an alphanumeric input - you are to apply run length encoding to encode the input argument.
Caveat:
The encoded value has to be <= input length. Should pass test case for following inputs: abcde 141414