-3

目前正在学习 Java,对这个相当基本的 RLE 程序有困难。我认为错误与重置字符数有关吗?它似乎正在输出应该被移走的以前的值。

请帮忙!我觉得自己太笨了,我不知道如何解决它哈哈

例如格式化: AABCEDDDGHIIIIII 将被转换为 A2B1C1E1D3G1H1I5

import java.util.Scanner;

class Main {
  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    
    System.out.println("Enter string for encoding: ");
    String uString = input.next();

    int count = 1;
    String eString = "";

    for (int i = 0; i < uString.length(); i++){
      if ((i != 0) && (uString.charAt(i) == uString.charAt(i-1))){
        count++;
      }else if(i!= 0){
        eString = eString + uString.charAt(i) + String.valueOf(count);
        count = 1;
      }
      System.out.println(String.valueOf(uString.charAt(i)) + String.valueOf(i) + String.valueOf(count)); //just to see what's happening in my code
    }System.out.println("Unencoded string's length: " + uString.length() + "\nEncoded string:" + eString + ", encoded string's length: " + eString.length());
  }
}```
4

1 回答 1

0

逻辑中的主要错误是此代码缺少每个递增的当前字符。count

因此,在该行eString = eString + uString.charAt(i) + String.valueOf(count);中,下一个字符被添加到结果字符串中。

可以通过在循环之前添加第一个字符、从索引 1 开始循环并在循环之后添加计数器来修复逻辑。

if (i != 0)然后可以完全删除条件:

String eString = "";

if (!uString.isEmpty()) {// there's something to count

    int count = 1;
    String eString = "" + uString.charAt(0);

    for (int i = 1, n = uString.length(); i < n; i++) {
        if (uString.charAt(i) == uString.charAt(i-1)) {
            count++;
        } else {
            // append count for previous character and then the current char
            eString = eString + count + uString.charAt(i);
            count = 1;
        }
        System.out.println(String.valueOf(uString.charAt(i)) + i + count); //just to see what's happening in my code
    }
    eString = eString + String.valueOf(count);
}
System.out.println("Unencoded string's length: " + uString.length() + "\nEncoded string:" + eString + ", encoded string's length: " + eString.length());

另一种方法是使用的嵌套循环(以及StringBuilder更有效地连接字符和计数器):

StringBuilder sb = new StringBuilder();
for (int i = 0, n = uString.length(); i < n; i++) {
    int count = 1;
    char c = uString.charAt(i);
    // loop without body just to increment counter
    for (int j = i + 1; j < n && uString.charAt(j) == c; j++, i++, count++);

    sb.append(c).append(count);
}
String eString = sb.toString();
于 2021-09-16T14:53:12.417 回答