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 start from the top of the code and go all the way down.
- Two variables created; <em>maxCharacterCount</em> to count the longest character in the string, and <em>longestSubString</em> to save the current longest substring. Initially they are set to 0 and the first character of given string respectively.
- We need to check all the substrings to find longest one. That is why a <u>nested for loop</u> (for loop inside a for loop) is created.
- The first loop starts from the first character of the given string and goes until the end of the given string.
- Inside the first loop, <em>currentMaxCharacterCount</em> is created to hold the current value of the maximum character in the given string.
- The second loop starts from the second character of the string, and checks if the character is same as the one that is being checked by the first loop.
- If they are not same, then the loop stops.
- If they are the same characters, <em>currentMaxCharacterCount</em> is incremented by 1. (That means we may find our new longest substring)
* Reminder: When the <em>i</em> is equal to 0, <em>j </em>is increasing from 1 to given string length. When <em>i</em> is equal to 1 <em>j</em> is increasing from 2 to given string length and so on. This process repeats for all <em>i</em> and <em>j</em> values to find out the longest substring.
- If <em>currentMaxCharacterCount </em>is greater than<em> maxCharacterCount, </em>that means we have a new longest substring, and <em>maxCharacterCount </em>should be equal to this new substring's count.
- Then, to be able to check for the next possible longest substring, it should continue from the next iteration of the <em>i </em>(longestSubString = str.charAt(i);)
- Finally, when the loops are done checking, <em>longestSubString</em> and <em>maxCharacterCount</em> need to be printed.