Learn AP Comp Sci

☰

Problem of the Day

Wednesday, November 4, 2026


Problem:

Consider the following method, which is intended to count the number of double-letter occurrences in a string.

/**
* returns the number of double-letter occurrences in a string
* Examples: "Ramadan" returns 0, repeated letters aren't sequential
* "Christmas" return 0
* "Hannukah" return 1 for the double "n"
* "Halloween" returns 2 for the doubled "l" and doubled "e"
*/
public static int doubleLetterCounter(String str)
{

/* missing code */

}

Which of the following could be used to replace /* missing code */ so that the method will work as intended?


  1. int count = 0;
    for (int i = 0; i < str.length(); i++)
    {
    if (str.substring(i - 1, i).equals(str.substring(i, i + 1)))
    count++;
    }
    return count;

  2. int count = 0;
    for (int i = 0; i < str.length(); i++)
    {
    if (str.substring(i, i + 1).equals(str.substring(i + 1, i + 2)))
    count++;
    }
    return count;

  3. int count = 0;
    for (int i = 1; i < str.length(); i++)
    {
    if (str.substring(i - 1, i).equals(str.substring(i, i + 1)))
    count++;
    }
    return count;

  4. int count = 0;
    for (int i = 1; i < str.length() - 1; i++)
    {
    if (str.substring(i - 1, i).equals(str.substring(i, i + 1)))
    count++;
    }
    return count;

Show solution:

The correct answer is c. While solution (d) also provides correct responses for the given test cases, it doesn't go through the entire string. Additional test data such as "Kwanzaa", with a double letter at the end, would not be identified by solution (d).