【问题标题】:Java run length decoding (expanding a compressed string)Java运行长度解码(扩展压缩字符串)
【发布时间】:2018-03-04 22:57:39
【问题描述】:
public static String decompressString (String text) {
    int count = 0;
    StringBuilder result = new StringBuilder () ;
    for (int i = 0; i < text.length(); i++) {
        char c = text.charAt(i);
        if (Character.isDigit(c)) {
            count = count * 10 + c - '0';
        } else { 
            while (count >0){ 
                result.append(c);
                count--;
            }
        }

    }
    return result.toString();
}

该程序应该从 main 方法(例如 5A5Bcd)中获取一个运行长度编码的字符串,并以运行长度解码的格式返回该字符串。 5A5Bcd -> AAAAABBBBBcd。我遇到的问题是代码似乎忽略了前面没有数字的字符。在上面的示例中,我返回 AAAAABBBBB 而不是 AAAAABBBBBcd; 'c' 和 'd' 前面没有数字,因此无法识别。任何想法,我已经被困在这一点上很长一段时间了。

【问题讨论】:

    标签: java decoding run-length-encoding


    【解决方案1】:

    当您在示例中遇到“c”和“d”字符时,您的count 变量不会非零,因为在处理“5B”后它会减为零。

    我在您的代码中看到的最简单的解决方法是在 while 循环之前添加一个检查:

    if (Character.isDigit(c)) {
        // ...
    } else {
        if (count == 0) {
            // Single-run-length characters have an implicit "1" prepended
            count = 1;
        }
        while (count > 0) {
            // ..
        }
    }
    

    【讨论】:

      【解决方案2】:

      每当您开始处理一个新角色时,计数为 0,因此不会追加任何内容。您希望在循环开始时 count 为 1,并在 while(count > 0) 循环后将其设置为 1。 你能解释一下你为什么这样做吗 计数 = 计数 * 10 + c - '0'; 而不是 count = c(这也必须更改)?

      【讨论】:

      • count = count * 10 + c - '0' 表示多于一位的数字,例如 10、100、1000 等。Ian 和你都帮助了我,代码正在运行现在想要的。谢谢你们。
      【解决方案3】:

      您可以通过以下方式解决此问题

      private static String decode(String encodedString) {
              String decodedString = null;
              //aaabbbcccccdd
              //3a3b5c2d
              
              int n = encodedString.length();
              StringBuilder sb= new StringBuilder();
              for (int i = 0; i < n; i++) {
                  if(i+1 <n && i%2 ==0)
                  sb.append(repeat(Integer.parseInt(String.valueOf(encodedString.charAt(i))),encodedString.charAt(i+1)));
              }
              
              return sb.toString();
                      
          }
      
          private static String repeat(int length, char charAt) {
              StringBuilder sb = new StringBuilder();
              for (int j = 0; j < length; j++) {
                  sb.append(charAt);
              }
              return sb.toString();
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-10-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多