On CodingBat.com there's a problem that asks for the length of the longest sequence of repeating characters within a string:
(https://codingbat.com/prob/p179479)
Given a string, return the length of the largest "block" in the string. A block is a run of adjacent chars that are the same.
maxBlock("hoopla") → 2
maxBlock("abbCCCddBBBxx") → 3
maxBlock("") → 0
This is the solution I wrote:
public int maxBlock(String str) {
int max = 0;
for(int i = 0; i < str.length(); i++)
{
char c = str.charAt(i);
int j = i + 1;
int possibleMax = 1;
// iterate through a "block"
while(j < str.length() && str.charAt(j) == c)
{
possibleMax++;
j++;
}
// if the block's length is greater than any found, save it
if(possibleMax > max)
max = possibleMax;
}
return max;
}
The time complexity is at least O(N) but I'm not sure if the while loop inside makes it O(N^2).
j++;
be executed? Can you speed up your program? $\endgroup$