1

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.

3
  • 1
    Why should that input return 4? The longest run appears to be "GGGGGGGGG", I assume you should save and reset the counter which you get a non-matching letter. Commented Nov 2, 2018 at 11:59
  • 1
    I suppose you want the very first occurrence of the group for the reqd. char and not the other ones. If yes, then you should break the loop after the first group ends. Commented Nov 2, 2018 at 12:00
  • Try adding something like this within the if block: System.out.printf("%d, %d, %c", i, counter, str.charAt(i)); You'll then see the counter and character printed for each step of the loop. You'll quickly see what the problem is. Commented Nov 2, 2018 at 12:10

1 Answer 1

5

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.