Answer:
public static void longestStreak(String str){
int maxCharacterCount = 0;
char longestSubString = str.charAt(0);
for(int i=0; i<str.length(); i++){
int currentMaxCharacterCount = 1;
for(int j=i+1; j<str.length(); j++){
if(str.charAt(i) != str.charAt(j)){
break;
}
else {
currentMaxCharacterCount++;
}
}
if (currentMaxCharacterCount > maxCharacterCount) {
maxCharacterCount = currentMaxCharacterCount;
longestSubString = str.charAt(i);
}
}
System.out.println(longestSubString + " "+ maxCharacterCount);
}
Explanation:
Let’s examine the code from start to finish.
- Two variables are initialized: maxCharacterCount to keep track of the longest character sequence in the string, and longestSubString which holds the longest substring found so far. They start at 0 and the first character of the string, respectively.
- The purpose is to check for all substrings to find the longest one. Hence, a nested for loop is employed (a loop within another loop).
- The outer loop commences at the first character of the input string, extending to its end.
- Within this outer loop, currentMaxCharacterCount counts the currently observed maximum character repetitions.
- The inner loop kicks off from the next character and verifies if it matches the character currently being examined in the outer loop.
- The loop halts if there’s a difference.
- If they match, currentMaxCharacterCount increments by 1, suggesting a possible new longest substring
* Note: When i equals 0, j grows from 1 up to the length of the string. When i is 1, j goes from 2 to the string length, and this cycle continues for all i and j.
- If currentMaxCharacterCount surpasses maxCharacterCount, it indicates a new longest substring, and maxCharacterCount ought to reflect this new count.
- To proceed to look for the subsequent longest substring, it carries on with the next iteration of i (longestSubString = str.charAt(i);)
- Ultimately, once both loops are finished, longestSubString and maxCharacterCount should be displayed.