CodePudding user response:
You're not correctly resetting your currentBlock
count. You need to reset the currentBlock
to 1
if the following character is different from the current one. If not, you need to continue increasing currentBlock
:
public int maxBlock(String str) {
int maxBlock = 0;
int currentBlock = 1;
if (str.length() < 1) {
return maxBlock;
} else {
maxBlock = 1;
}
for (int i = 0; i < str.length() - 1; i ) {
if (str.charAt(i) == str.charAt(i 1)) {
currentBlock ;
if (currentBlock > maxBlock) {
maxBlock = currentBlock;
}
} else {
currentBlock = 1;
}
}
return maxBlock;
}
CodePudding user response:
Although I think @Robby Cornelissen and @Eskandar Abedini's solutions are definitely more viable than mine and closer to the original code, I would like to chip in to offer a different approach by using regex and a bit of coding logic.
The following regex looks for a match where a character reappears 0 or more times. This could be employed with the results()
method of the Matcher
class to extract the longest match found.
Here is a link to test the regex
https://regex101.com/r/OcMoQ9/1
Code Implementation
List<String> testCase = List.of("hoopla", "abbCCCddBBBxx", "", "xyz", "xxyz", "xyzz", "abbbcbbbxbbbx", "XXBBBbbxx", "XXBBBbbxxXXXX", "XX2222BBBbbXX2222");
Pattern pattern = Pattern.compile("(.)(\\1*)");
Matcher matcher;
for (String s : testCase) {
matcher = pattern.matcher(s);
System.out.printf("%s => %d%n", s, matcher
.results()
.map(match -> match.group().length())
.max(Comparator.comparing(Integer::intValue))
.orElse(0));
}
Link to Test the code
https://www.jdoodle.com/iembed/v0/rH7
Output
hoopla => 2
abbCCCddBBBxx => 3
=> 0
xyz => 1
xxyz => 2
xyzz => 2
abbbcbbbxbbbx => 3
XXBBBbbxx => 3
XXBBBbbxxXXXX => 4
XX2222BBBbbXX2222 => 4
CodePudding user response:
This code is generated by GitHub Copilot plugin for IntelliJ, you need just type int maxBlock
then GitHub Copilot generates rest of the code:
private int maxBlock(String s) {
if (s == null || s.length() == 0) return 0;
int maxBlocks = 0;
int currentBlocks = 0;
char currentChar = s.charAt(0);
for (int i = 0; i < s.length(); i ) {
if (s.charAt(i) == currentChar) {
currentBlocks ;
} else {
currentBlocks = 1;
currentChar = s.charAt(i);
}
maxBlocks = Math.max(maxBlocks, currentBlocks);
}
return maxBlocks;
}
I only added if (s == null || s.length() == 0) return 0;
to generated code.