Java RLE升级算法

时间:2017-04-20 08:58:18

标签: java url-encoding

例如,如果我有如下输入:

  

Heeeeeeeeeeeellooooo

输出必须是:

  

H9e3e2l5o

这是我到目前为止编写的代码:

    public class RLE {
        public static String encode(String s) {
            if (s == "" || s == null) return "";
            StringBuilder sb = new StringBuilder();
            int count = 1;
            char previous = s.charAt(0);
            char current;

            for (int i = 1; i < s.length(); i++) {
                current = s.charAt(i);
                if (current == previous) {
                    count++;
                } else {
                    if (count == 1) {
                        sb.append(previous);
                    } else if (count > 1) {
                        sb.append(count).append(previous);
                        count = 1;
                    }
                }
                previous = current;

            }

            return sb.toString();
        }

结果:

  

&#39; Heeeeeeeeeeeellooooo&#39; - &GT; H12e2l

3 个答案:

答案 0 :(得分:2)

这对你有用

public static String encode(String s) {
    if (s == "" || s == null)
        return "";
    StringBuilder sb = new StringBuilder();
    int count = 1;
    char previous = s.charAt(0);
    char current;

    for (int i = 1; i < s.length(); i++) {
        current = s.charAt(i);
        if (current == previous) {
            count++;
        } else {
            if (count == 1) {
                sb.append(previous);
            } else if (count > 1) {
                if (count > 9) {
                    sb.append(9).append(previous);
                    sb.append(count - 9).append(previous);
                } else {
                    sb.append(count).append(previous);
                }
                count = 1;
            }
        }
        previous = current;

    }
    sb.append(count).append(previous);
    return sb.toString();
}

答案 1 :(得分:0)

缺少代码

if (count > 1) {
  sb.append(count);
}
sb.append(previous)
在for循环之后

答案 2 :(得分:0)

你错过了字符串的最后一个char等于前一个char然后不打印的情况。在if(current == previous)case case

中添加增量逻辑
                    if (current == previous) {
                    count++;
                    if(i == s.length()-1){
                        if (count == 1) {
                            sb.append(previous);
                        } else if (count > 1) {
                            sb.append(count).append(previous);
                            count = 1;
                        }
                    }
                }