问题:
从字符串 s
中删除子字符串 t
,重复并打印执行相同操作所涉及的步骤数。
解释/工作:
For Example:
t = ab
,s = aabb
. In the first step, we check ift
is contained withins
. Here,t
is contained in the middle i.e.a(ab)b
. So, we will remove it and the resultant will beab
and increment thecount
value by 1. We again check ift
is contained withins
. Now,t
is equal tos
i.e.(ab)
. So, we remove that froms
and increment thecount
. So, sincet
is no more contained ins
, we stop and print thecount
value, which is 2 in this case.
所以,这是我尝试过的:
代码 1:
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; }
由于某种原因,我只能通过 Hackerrank 上的 9/14 测试用例(对于其余的用例,我得到的是“错误答案”)。过了一段时间,我发现Java中有一个叫做
replace()
的方法。因此,我尝试通过替换if
条件来使用它,并提出了第二个版本的代码。代码 2:
static int maxMoves(String s, String t) { int count = 0,i; while(true) { if(s.contains(t)) s.replace(t,""); //Marked Statement else break; ++count; } return count; }
但由于某些原因(我不知道为什么),上面代码中的“标记语句”被无限执行(这是我在替换“标记语句”时注意到的) 与
System.out.println(s.replace(t,""));
)。我不明白同样的原因。
因为我只通过了 9/14 测试用例,所以一定有一些逻辑错误导致“错误答案”。如果我使用 代码 1,我该如何克服这个问题?如果我使用代码 2,如何避免无限执行 “标记语句”?或者有人愿意向我推荐 Code 3 吗?
提前谢谢你:)
最佳答案
尝试保存新的(返回的)字符串而不是忽略它。
s = s.replace(t,"");
replace 返回一个新的字符串;您似乎认为它就地改变了给定的字符串。
关于java - 重复从字符串中删除子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46161057/