Java 编码BAT maxBlock
我一直在做一些编码练习,我遇到了这个问题。 给定一个字符串,返回字符串中最大块的长度。块是相同的相邻字符的运行。 所需输出:Java 编码BAT maxBlock,java,Java,我一直在做一些编码练习,我遇到了这个问题。 给定一个字符串,返回字符串中最大块的长度。块是相同的相邻字符的运行。 所需输出: maxBlock("hoopla") → 2 maxBlock("abbCCCddBBBxx") → 3 maxBlock("") → 0 除了最后一个测试外,我的代码似乎通过了所有测试。请有人检查一下我的代码,告诉我哪里出了问题 提交代码: public int maxBlock(String str) { int charBlock = 0;
maxBlock("hoopla") → 2
maxBlock("abbCCCddBBBxx") → 3
maxBlock("") → 0
除了最后一个测试外,我的代码似乎通过了所有测试。请有人检查一下我的代码,告诉我哪里出了问题
提交代码:
public int maxBlock(String str) {
int charBlock = 0;
int holder = 1;
if(str.length() == 0){ //If string is empty return 0
charBlock = 0;
} else if(str.length() == 1){ //If string contains only a single char return 1
charBlock = 1;
} else {
for(int i=0; i < str.length()-1; i++){ //loop through each char value
if((str.length() == 2) && (str.charAt(i) != str.charAt(i+1))){
charBlock =1; //return 1 if the length of the string is 2 and non of the two chars match
}
else if((str.length() == 3) && (str.charAt(i) != str.charAt(i+1))){
charBlock = 1; //return 1 if the length of the string is 3 and non of the three chars match
}
else if (str.charAt(i) == str.charAt(i+1)){
holder = holder + 1;
if(holder > charBlock){
charBlock = holder; //update the value of charBlock if a holder is larger current value
}
} else holder = 1;
}
}
return charBlock;
}
Expected Run
maxBlock("hoopla") → 2 2 OK
maxBlock("abbCCCddBBBxx") → 3 3 OK
maxBlock("") → 0 0 OK
maxBlock("xyz") → 1 1 OK
maxBlock("xxyz") → 2 2 OK
maxBlock("xyzz") → 2 2 OK
maxBlock("abbbcbbbxbbbx") → 3 3 OK
maxBlock("XXBBBbbxx") → 3 3 OK
maxBlock("XXBBBBbbxx") → 4 4 OK
maxBlock("XXBBBbbxxXXXX") → 4 4 OK
maxBlock("XX2222BBBbbXX2222") → 4 4 OK
other tests X
这可以更有效,尤其是使用帮助器方法!别想太多这个问题,我知道它很难。我的策略是获取这个字符的块,然后继续下一个字符
public int maxBlock(String str) {
if (str.length() == 0) {
return 0;
}
int biggest = Integer.MIN_VALUE;
for (int a = 0; a < str.length(); a++) {
biggest = Math.max(biggest, (countBlock(str, str.substring(a, a + 1), a));
}
return biggest; //by now we have the biggest
}
public int countBlock(String s, String any, int startIndex) {
int cnt = 1;
for (int a = startIndex + 1; a < s.length(); a++) { //start right after index
if (s.substring(a, a + 1).contains(any)){ //keep going
cnt++;
}
else if (!s.substring(a, a + 1).equals(any)) { //stop here
break;
}
}
return cnt;
}
您的代码很好,但不必要地检查输入字符串的长度。 这是您的代码,其中有一些改进
public int maxBlock(String str) {
int holder = 1;
int charBlock = 0;
for(int i=0; i < str.length()-1; i++){ //loop through each char value
if (str.charAt(i) == str.charAt(i+1)){
holder++;
}else{
holder = 1;
}
if(holder > charBlock){
charBlock = holder; //update the value of charBlock if a holder is larger current value
}
}
return charBlock;
}
我不知道最后一个测试是什么,但如果它调用maxBlocknull;,它会失败的。这个问题似乎是离题的,因为它是关于代码审查的,这可能更适合。谢谢@ZouZou。我也不知道最后一次测试到底在测试什么。你知道我如何解决maxBlocknull的问题吗;或者帮助我理解它为什么失败?如果你传递null,你认为str.length会做什么?我建议您试试。@ZouZou好的,我添加了ifstr.equalsnull{charBlock=0;}来绕过这个场景。