118k views
4 votes
The method longestStreak is intended to determine the longest substring of consecutive identical characters in the parameter str and print the result.

For example, the call longestStreak("CCAAAAATTT!") should print the result "A 5" because the longest substring of consecutive identical characters is "AAAAA".

Complete the method below. Your implementation should conform to the example above.

public static void longestStreak(String str)

User Tubbs
by
4.3k points

1 Answer

0 votes

Final answer:

The longestStreak method should count consecutive identical characters in a string, keeping track of the longest streak found and the character associated with that streak. An implementation example in Java was provided. When passed the string "CCAAAAATTT!", it prints "A 5".

Step-by-step explanation:

The question asks to complete a method longestStreak in Java that determines and prints the longest substring of consecutive identical characters in a given string. This can be achieved by iterating through the string and counting the consecutive characters, updating the count and character when a longer streak is found. Below is a possible implementation of the method:

public static void longestStreak(String str) {
int maxStreak = 0;
char maxChar = str.charAt(0);
int currentStreak = 1;

for (int i = 1; i < str.length(); i++) {
if (str.charAt(i) == str.charAt(i - 1)) {
currentStreak++;
} else {
currentStreak = 1;
}
if (currentStreak > maxStreak) {
maxStreak = currentStreak;
maxChar = str.charAt(i - 1);
}
}
System.out.println(maxChar + " " + maxStreak);
}

When the longestStreak method runs with the input "CCAAAAATTT!", it will print "A 5" showing that 'A' is the character that appears the most consecutively in a streak, which is 5 times in a row.

User Lefticus
by
4.4k points