65.9k views
2 votes
SHOW ALL YOUR WORK. REMEMBER THAT PROGRAM SEGMENTS ARE TO BE WRITTEN IN JAVA.

Assume that the classes listed in the Java Quick Reference have been imported where appropriate.
Unless otherwise noted in the question, assume that parameters in method calls are not null and that methods are called only when their preconditions are satisfied.
In writing solutions for each question, you may use any of the accessible methods that are listed in classes defined in that question. Writing significant amounts of code that can be repl
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 atz is a properly initialized string variable. Your implementation should conform to the example
public static void longestStreak (String str)

1 Answer

5 votes

Answer: To find the longest substring of consecutive identical characters in a given string, you can use the following code segment: 1. Initialize variables to keep track of the longest streak and the current streak. Set both to 0. 2. Initialize a variable to store the character of the current streak. 3. Iterate through each character in the input string. 4. If the current character is equal to the character of the current streak, increment the current streak by 1. 5. If the current character is not equal to the character of the current streak, compare the current streak with the longest streak. 6. If the current streak is greater than the longest streak, update the longest streak and the character of the longest streak. 7. Reset the current streak to 1 and update the character of the current streak. 8. After the loop, compare the current streak with the longest streak one more time to handle the case where the longest streak occurs at the end of the string. 9. Print the character of the longest streak and its length. Here's an example implementation of the code segment: ``` public static void longestStreak(String str) { int longestStreak = 0; int currentStreak = 0; char currentChar = '\0'; // initialize with a null character for (char c : str.toCharArray()) { if (c == currentChar) { currentStreak++; } else { if (currentStreak > longestStreak) { longestStreak = currentStreak; } currentStreak = 1; currentChar = c; } } if (currentStreak > longestStreak) { longestStreak = currentStreak; } System.out.println("Longest streak: " + currentChar + " " + longestStreak); } ``` For example, if you call `longestStreak("CCAAAAATTT!")`, the code will output "A 5" because the longest substring of consecutive identical characters is "AAAAA".

User John Melville
by
8.4k points