Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

run length encoding #109

Open
knasim opened this issue Nov 9, 2018 · 2 comments
Open

run length encoding #109

knasim opened this issue Nov 9, 2018 · 2 comments

Comments

@knasim
Copy link

knasim commented Nov 9, 2018

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

@knasim
Copy link
Author

knasim commented Nov 9, 2018

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();

`

@ctfloyd
Copy link

ctfloyd commented Nov 13, 2018

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.

@knasim knasim changed the title a new one run length encoding Nov 29, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants