【问题标题】:Compress the string in java在java中压缩字符串
【发布时间】:2021-04-13 08:46:15
【问题描述】:

请帮忙看看下面的java代码。
例如,当我输入 aabbcccd 时, 输出是 99100102d,但应该是 a2b2c3d。 谁能告诉我这段代码的错误是什么? (此代码尝试捕获输入和输出特定字符的输入频率)

import java.util.*;

public class Main {

    public static void main(String args[]) {
        try {
            Scanner scn = new Scanner(System.in);
            String s = scn.nextLine();                     // taking input
            StringBuilder str = new StringBuilder(s);              
            StringBuilder str_new = new StringBuilder();

            int i = 0 ;
            while (i < str.length()) {
                int count = 1; 
                while (i < str.length()-1 && str.charAt(i) == str.charAt(i+1)){
                    count += 1;
                    i++;
                }
                if (count == 1)
                    str_new.append(str.charAt(i));
                else
                    str_new.append(str.charAt(i) + (char)count);
                i++;
            }
            System.out.println(str_new);
        } catch (Exception e) {
            return;
        }
    }
}

【问题讨论】:

  • 您好,您现在已经有了答案,您可以考虑accepting an answer 来奖励给您最有帮助的评论。

标签: java string stringbuilder


【解决方案1】:

问题来自str.charAt(i) + (char)count,因为它们是2个字符,所以用它们的int值相加,


通过使用连续的append() 调用来解决这个问题

str_new.append(str.charAt(i)).append(count);

您可以通过在append 中使用外部for-loop 和三元运算符来减少代码,并在内部while 中仅增加i,方法是在之前保存i

int count;
for (int i = 0; i < str.length(); i++) {
    count = i;
    while (i < str.length() - 1 && str.charAt(i) == str.charAt(i + 1)) {
        i++;
    }
    str_new.append(str.charAt(i)).append((i - count) == 0 ? "" : (i - count + 1));
}

【讨论】:

    【解决方案2】:

    您的主要问题是使用了StringBuilder 并输入了我在此示例中显示的值。但在这种情况下,我使用的是正则表达式。

    • (.) 是一个匹配任何字符的捕获块
    • \\1* 指的是第一个捕获块后跟 0 个或多个相同字符。

    以下代码为输入的文本构造匹配器,然后继续查找后续匹配项。它们可以按找到的方式打印出来,也可以按照我的选择放在StringBuilder 中。

    Scanner scn = new Scanner(System.in);
    String text = scn.nextLine();
    
    Matcher m = Pattern.compile("(.)\\1*").matcher(text);
    
    StringBuilder sb = new StringBuilder();
    while (m.find()) {
        String s = m.group();
        int count = s.length();
        sb.append(s.charAt(0)).append(count > 1 ? count : "");
    }
    
    System.out.println(sb.toString());
    

    用于aaabbbbcadb 打印

    a3b4cadb
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-25
      • 1970-01-01
      • 1970-01-01
      • 2011-04-07
      • 1970-01-01
      • 2019-10-15
      相关资源
      最近更新 更多