我正在使用 codingbat.com 进行一些 java 练习。字符串问题之一“withoutString”如下所示:
给定两个字符串,base 和 remove,返回一个版本的 base 字符串,其中 remove 字符串的所有实例都已被删除(不区分大小写)。 您可以假设删除字符串的长度为 1 或更长。仅删除不重叠的实例,因此使用“xxx”删除“xx”会留下“x”。 可以在以下位置找到此问题:http://codingbat.com/prob/p192570
正如您从下面链接到 dropbox 的屏幕截图中看到的那样,除了三个和最后一个称为“其他测试”的运行之外,所有运行都通过了。问题是,即使它们被标记为不正确,我的输出与正确答案的预期输出完全匹配。
这是我的输出截图:
这是我使用的代码:
public String withoutString(String base, String remove) {
String result = "";
int i = 0;
for(; i < base.length()-remove.length();){
if(!(base.substring(i,i+remove.length()).equalsIgnoreCase(remove))){
result = result + base.substring(i,i+1);
i++;
}
else{
i = i + remove.length();
}
if(result.startsWith(" ")) result = result.substring(1);
if(result.endsWith(" ") && base.substring(i,i+1).equals(" ")) result = result.substring(0,result.length()-1);
}
if(base.length()-i <= remove.length() && !(base.substring(i).equalsIgnoreCase(remove))){
result = result + base.substring(i);
}
return result;
}
最佳答案
您的解决方案失败并且编码 bat 时存在显示错误。
正确的输出应该是:
withoutString("This is a FISH", "IS") -> "Th a FH"
你的是:
withoutString("This is a FISH", "IS") -> "Th a FH"
你的失败是因为它正在删除空格,而且由于 HTML 删除了额外的空格,编码 bat 不会显示正确的预期和运行输出字符串。
这个递归解决方案通过了所有测试:
public String withoutString(String base, String remove) {
int remIdx = base.toLowerCase().indexOf(remove.toLowerCase());
if (remIdx == -1)
return base;
return base.substring(0, remIdx ) +
withoutString(base.substring(remIdx + remove.length()) , remove);
}
这是最佳迭代解决方案的示例。它的代码比递归解决方案多,但速度更快,因为调用的函数要少得多。
public String withoutString(String base, String remove) {
int remIdx = 0;
int remLen = remove.length();
remove = remove.toLowerCase();
while (true) {
remIdx = base.toLowerCase().indexOf(remove);
if (remIdx == -1)
break;
base = base.substring(0, remIdx) + base.substring(remIdx + remLen);
}
return base;
}
关于Java codingbat 帮助 - withoutString,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20648078/