【发布时间】:2018-04-01 21:59:16
【问题描述】:
问题:从字符串s 中删除子字符串t,重复并打印执行相同操作所涉及的步骤数。
示例: t = ab、s = aabb。第一步,我们检查t 是否包含在s 中。这里,t 包含在中间,即a(ab)b。因此,我们将删除它,结果将是ab,并将计数值增加1。我们再次检查t 是否包含在s 中。现在,t 等于s,即(ab)。所以,我们从s 中删除它并增加计数。因此,由于t 不再包含在s 中,我们停止并打印计数值,在本例中为2。
我尝试使用递归来解决这个问题
static int maxMoves(String s, String t) {
if ( null == s || "" == s || null == t || "" == t){
return 0;
}
int i = s.indexOf(t);
if(i != -1) {
return maxMoves(s.substring(0, i)+ s.substring(i+t.length(), s.length()), t) + 1;
} else {
return 0;
}
}
但我只通过了 9/14 的测试用例。这个我也试过了,
static int maxMoves(String s, String t) {
int count = 0,i;
while(true)
{
if(s.contains(t))
{
i = s.indexOf(t);
s = s.substring(0,i) + s.substring(i + t.length());
}
else break;
++count;
}
return count;
}
但这也只通过了 9/14 例。
谁能帮我弄清楚我没有涵盖哪些案例?
【问题讨论】:
-
为什么不使用String#replace
-
"" == s-> How do I compare strings in Java?,或者在这种情况下s.isEmpty()更清晰。 -
是的,我改变了它,但仍然只有 9/14 案例通过。我不认为正在检查空字符串。
标签: java string recursion substring