【问题标题】:Sequence Count - Char in String java序列计数 - 字符串 java 中的字符
【发布时间】:2018-11-02 11:55:45
【问题描述】:

我有以下任务: 计算给定字符在给定字符串中出现的次数。 “运行”是一个或多个相同字符出现的连续块。例如,如果字符串为“AATGGGGCCGGTTGGGGGGGGAGAGC”且字符为“G”,则返回 4。 没有导入,'?'允许 我的尝试:

public static int charRunCount(String str, char c){
    int counter = 0;
    for (int i = 0; i < str.length()-1; i++) {
        if ( (str.charAt (i) == str.charAt (i+1)) && str.charAt (i)==c )
            counter+=1;
    }
    return counter;
}

输出 =12, 请帮助修复或更正。

【问题讨论】:

  • 为什么输入应该返回 4?最长的运行似乎是“GGGGGGGGGG”,我认为您应该保存并重置您收到不匹配字母的计数器。
  • 我想你想要 reqd 组的第一次出现。 char 而不是其他的。如果是,那么你应该在第一组结束后打破循环。
  • 尝试在if 块中添加类似的内容:System.out.printf("%d, %d, %c", i, counter, str.charAt(i)); 然后您将看到为循环的每个步骤打印的计数器和字符。您很快就会发现问题所在。

标签: java string char sequence counter


【解决方案1】:

您想计算特定角色开始运行的次数。跑步的长度无关紧要。

public static int charRunCount(String str, char c) {
    char last = 0;
    int counter = 0;
    for (int i = 0; i < str.length(); i++) {
        // whenever a run starts.
        if (last != c && str.charAt(i) == c)
            counter++;
        last = str.charAt(i);
    }
    return counter;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-12
    • 2020-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多