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

Yuk*_*112 1 java string counter char sequence

我有以下分配:计算给定字符中有多少“游程”出现在给定字符串中。“运行”是一个或多个相同字符的连续块。例如,如果字符串是“ AATGGGGCCGGTTGGGGGGGGGGGAAGC”,字符是“ 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;
}
Run Code Online (Sandbox Code Playgroud)

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

Pet*_*rey 5

您要计算运行特定角色的次数。运行时间长短无关紧要。

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;
}
Run Code Online (Sandbox Code Playgroud)