这是CodingBat网站的一个问题.我先把问题粘在一边,然后讨论我的努力:
给定两个字符串base和remove,返回基本字符串的一个版本,其中删除了删除字符串的所有实例(不区分大小写).您可以假设删除字符串的长度为1或更长.仅删除不重叠的实例,因此使用"xxx"删除"xx"会留下"x".
Run Code Online (Sandbox Code Playgroud)withoutString("Hello there", "llo") ? "He there" withoutString("Hello there", "e") ? "Hllo thr" withoutString("Hello there", "x") ? "Hello there"
这是我到目前为止写的:
public String withoutString(String base, String remove) {
int len_b=base.length();
int len_r = remove.length();
String result="";
if(len_b<1 || len_r<1)
return "";
for (int i =0;i<=len_b-len_r;i++)
{
if(base.substring(i,i+len_r).equals(remove))
{
i=i+len_r-1;
}
else
{
result=result+base.substring(i,i+1);
}
}
if(!(base.substring(len_b-len_r+1, len_b).equals(remove)))
result=result+base.substring(len_b-len_r+1, len_b);
return result;
}
Run Code Online (Sandbox Code Playgroud)
这会传递所有测试用例,除了删除字符串不区分大小写的情况.
例如: withoutString("This is a FISH", "IS") ? "Th a FH"
我的代码给了我"这是一个FH",因为我在代码中没有处理区分大小写.我知道使用Regex可以在一行中完成.我更感兴趣的是知道在我现在的代码中是否有办法处理这些类型的测试用例.另外,如果我的代码更高效/更优雅,请告诉我.
| 归档时间: |
|
| 查看次数: |
2852 次 |
| 最近记录: |