反复从字符串中删除子字符串 [英] Removing a substring from a string, repeatedly
问题描述
问题:
从字符串 s
中删除子字符串 t
,然后重复打印并执行相同操作。
Problem:
Remove the substring t
from a string s
, repeatedly and print the number of steps involved to do the same.
说明/工作方式:
例如:
t = ab
,s = aabb
。第一步,我们检查t
是否包含在s
中的
。在这里,t
包含在中间,即a(ab)b
。
因此,我们将其删除,结果将是ab
并增加
count
值乘以1。我们再次检查s
中是否包含t
。现在,t
是
等于s
即(ab)
。因此,我们将其从s
中删除,然后增加
count
的数量。因此,由于t
不再包含在s
中,因此我们停止打印
count
值,在这种情况下为2。
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:
Code 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
条件来使用它,并提出了第二个版本的代码。
I am just able to pass 9/14 test cases on Hackerrank, due to some reason (I am getting "Wrong Answer" for rest of the cases). After a while, I found out that there is something called replace()
method in Java. So, I tried using that by replacing the if
condition and came up with a second version of code.
代码2:
Code 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,));
)。我没有相同的理由。
But for some reason (I don't know why), the "Marked Statement" in the above code gets executed infinitely (this I noticed when I replaced the "Marked Statement" with System.out.println(s.replace(t,""));
). I don't the reason for the same.
因为我只通过了9/14个测试用例一定是导致错误答案 的逻辑错误。如果使用代码1 ,该如何克服?如果我使用代码2 ,该如何避免无限执行标记语句 ?还是有人愿意向我建议代码3 ?
Since, I am passing only 9/14 test cases, there must be some logical error that is leading to a "Wrong Answer". How do I overcome that if I use Code 1? And if I use Code 2, how do I avoid infinite execution of the "Marked Statement"? Or is there anyone who would like to suggest me a Code 3?
请先谢谢您:)
推荐答案
尝试保存新的(返回的)字符串,而不要忽略它。
Try saving the new (returned) string instead of ignoring it.
s = s.replace(t,"");
替换返回一个新字符串;您似乎认为它会就地改变给定的字符串。
replace returns a new string; you seemed to think that it alters the given string in-place.
这篇关于反复从字符串中删除子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!