java Run-length encoding

后端 未结 5 1319
臣服心动
臣服心动 2020-12-06 08:38

I have no idea how to start my assignment.

We got to make a Run-length encoding program,

for example, the users enters this string:

aaaaPPPrrrrr

5条回答
  •  孤街浪徒
    2020-12-06 09:21

    This can easily and simply be done using a StringBuilder and a few helper variables to keep track of how many of each letter you've seen. Then just build as you go.

    For example:

    static String encode(String s) {
        StringBuilder sb = new StringBuilder();
        char[] word = s.toCharArray();
        char current = word[0]; // We initialize to compare vs. first letter
    
               // our helper variables
        int index = 0; // tracks how far along we are
        int count = 0; // how many of the same letter we've seen
    
        for (char c : word) {
            if (c == current) {
                count++;
                index++;
    
                if (index == word.length)
                    sb.append(current + Integer.toString(count));
            }
    
            else {
                sb.append(current + Integer.toString(count));
                count = 1;
                current = c;
                index++;
            }
        }
        return sb.toString();
    }
    

    Since this is clearly a homework assignment, I challenge you to learn the approach and not just simply use the answer as the solution to your homework. StringBuilders are very useful for building things as you go, thus keeping your runtime O(n) in many cases. Here using a couple of helper variables to track where we are in the iteration "index" and another to keep count of how many of a particular letter we've seen "count", we keep all necessary info for building our encoded string as we go.

提交回复
热议问题