[英]Codingbat challenge: maxBlock
给定来自 CodingBat 的任务maxBlock :
给定一个字符串,返回字符串中最大“块”的长度。 块是一系列相同的相邻字符。
maxBlock("hoopla") → 2
maxBlock("abbCCCddBBBxx") → 3
maxBlock("") → 0
我的解决方案通过了所有测试,除了一个:
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;
currentBlock = 0;
}
}
}
return maxBlock;
}
您没有正确重置您的currentBlock
计数。 如果以下字符与当前字符不同,则需要将currentBlock
重置为1
。 如果没有,您需要继续增加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;
}
虽然我认为@Robby Cornelissen 和@Eskandar Abedini 的解决方案肯定比我的更可行并且更接近原始代码,但我想通过使用正则表达式和一些编码逻辑来提供一种不同的方法。
以下正则表达式查找字符出现 0 次或多次的匹配项。 这可以与Matcher
类的results()
方法一起使用,以提取找到的最长匹配项。
这是测试正则表达式的链接
https://regex101.com/r/OcMoQ9/1
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));
}
//Or even simpliefied like so as @Holger has pointed out in the comments
for (String s : testCase) {
matcher = pattern.matcher(s);
System.out.printf("%s => %d%n", s, matcher
.results()
.mapToInt(match -> match.group().length())
.max()
.orElse(0));
}
https://www.jdoodle.com/iembed/v0/rH7
hoopla => 2
abbCCCddBBBxx => 3
=> 0
xyz => 1
xxyz => 2
xyzz => 2
abbbcbbbxbbbx => 3
XXBBBbbxx => 3
XXBBBbbxxXXXX => 4
XX2222BBBbbXX2222 => 4
此代码由 IntelliJ 的GitHub Copilot插件生成,您只需键入int maxBlock
然后 GitHub Copilot 生成其余代码:
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;
}
我只添加了if (s == null || s.length() == 0) return 0;
到生成的代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.