我一直在经历一些编码蝙蝠练习,我遇到了这个问题。"给定一个字符串,返回字符串中最大"块"的长度。块是相同的相邻字符的运行。"所需输出:
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) {
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;
}
这可以更有效,尤其是使用助手方法!不要想得太多,我知道这很难。我的策略是得到这个字符的块,然后继续下一个。
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;
}