有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

字符串java中的序列计数字符

我的任务如下: 计算给定字符串中给定字符的“运行”次数。 “运行”是同一字符的一个或多个出现的连续块。例如,如果字符串为“AATGGGGCCGGTTGGGGGGGAAGC”,字符为“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, 请帮助修复或更正


共 (1) 个答案

  1. # 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;
    }