从字符串s中重复删除子串t,并打印执行此操作所需的步骤数。
说明/工作原理:
例如:t = ab,s = aabb。在第一步中,我们检查t是否包含在s中。这里,t包含在中间即a(ab)b。因此,我们将其删除,结果为ab,并将计数值增加1。我们再次检查t是否包含在s中。现在,t等于s即(ab)。因此,我们将其从s中删除并增加计数。因此,由于t不再包含在s中,我们停止并打印计数值,本例中为2。
所以,这是我尝试过的:
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; }
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 theif
condition and came up with a second version of code.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; }
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个测试用例,可能存在一些逻辑错误导致了"Wrong Answer"。如果我使用Code 1,我该如何克服这个问题?如果我使用Code 2,我该如何避免"Marked Statement"的无限执行?还是有人想建议我使用Code 3吗?
提前感谢你的帮助 :)
substring()
的两个索引都为0会发生什么? - Amin Negm-Awad