170k views
2 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".

Write the code segment to be used in the body of the method below. The parameter str is a properly initialized String variable. Your implementation should conform to the example above.

public static void longestStreak(String str)

Arrays can't be used to answer this question

User ConnorU
by
8.7k points

1 Answer

5 votes

Final answer:

The longestStreak method looks for consecutive identical characters in a string and prints the longest streak found. The code iterates through the string, counting streak lengths, and updates the maximum streak when necessary, before printing the result.

Step-by-step explanation:

The method longestStreak is designed to find the longest sequence of identical characters in a given string without using arrays. Here is how you can implement the code:

public static void longestStreak(String str) {
if (str == null || str.length() == 0) {
System.out.println(""0");
return;
}
int maxStreak = 1;
int currentStreak = 1;
char maxChar = str.charAt(0);

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);
}
}
System.out.println(maxChar + " " + maxStreak);
}

This code iterates through the characters of the provided string, counting the length of each streak and updating the maximum when a longer streak is found. Finally, it prints the character with the longest streak along with its length.

User Pranjal Mittal
by
7.9k points