java Run-length encoding

后端 未结 5 1310
臣服心动
臣服心动 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:36

    public String runLengthEncoding(String text) {
        String encodedString = "";
    
        for (int i = 0, count = 1; i < text.length(); i++) {
            if (i + 1 < text.length() && text.charAt(i) == text.charAt(i + 1))
                count++;
            else {
                encodedString = encodedString.concat(Integer.toString(count))
                        .concat(Character.toString(text.charAt(i)));
                count = 1;
            }
        }
        return encodedString;
    }
    

    Try this one out.

提交回复
热议问题