我的业务逻辑很怪异,但总之我会在这里解释。 我必须删除第一个或最后一个子字符串,然后重复该过程。我认为下面的代码到现在为止工作得很好。现在我想知道如何对它进行优化,因为对于大输入(字符串长度为10000)的数据来说效果不佳。通过在java中搜索和删除旧的子字符串来创建子字符串的最快方法是什么?
int count =0;
while(s.contains(substr))
{
s= s.replaceFirst(substr,"");
// doSomeBusinessLogic(s);
count++;
}
return count;
例子
test 1 s = abababab substr = ab count = 4 test 2 s = aeerrb substr = er count =2 because after removing first er, the string becomes aerb, so remove the er again. so count is 2.
Edited-按照它看起来像匹配是更好地使用,但是,它不是产生例外答案的答案。
public class Solution {
static int maxMoves(String s, String substr) {
int count = 0;
StringBuffer buf = new StringBuffer();
Matcher m = Pattern.compile(substr).matcher(s);
while (m.find()) {
m.appendReplacement(buf, "");
count++;
}
m.appendTail(buf);
// System.out.println(buf.toString());
return count;
}
public static void main(String[] args) {
System.out.println("Max Moves"+ Solution.maxMoves("aeerrb","er"));
}
}
你能提供输入和预期输出的一些例子吗? – Mandy8055
添加了示例 – irobo
s。[replaceAll(substr,“”)](https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#replaceAll(java.lang.String ,%20java.lang.String)) – Stefan