Reputation: 365
I have the following assignment: Count how many "runs" of the given character appear in the given string. A "run" is a consecutive block of one or more occurrences of the same character. For example, if the string is "AATGGGGCCGGTTGGGGGGGGGAAGC" and the character is "G", returns 4. No import, '?' is allowed My attempt:
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;
}
output =12, please help fix or correct.
Upvotes: 1
Views: 2038
Reputation: 533590
You want to count the number of times a run of a particular character starts. The length of the run doesn't matter.
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;
}
Upvotes: 5