2017-08-25 22 views
0

我的业务逻辑很怪异,但总之我会在这里解释。 我必须删除第一个或最后一个子字符串,然后重复该过程。我认为下面的代码到现在为止工作得很好。现在我想知道如何对它进行优化,因为对于大输入(字符串长度为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")); 

     } 



    } 
+0

你能提供输入和预期输出的一些例子吗? – Mandy8055

+0

添加了示例 – irobo

+0

s。[replaceAll(substr,“”)](https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#replaceAll(java.lang.String ,%20java.lang.String)) – Stefan

回答

1

免责声明:本答案的代码将无法处理,后来加入到这个问题的例子给出的测试2。

与您的代码,插入打印语句,你会得到:

String s = "This is a test"; 
String substr = " "; 

int count = 0; 
while (s.contains(substr)) { 
    s = s.replaceFirst(substr, ""); 
    System.out.println("doSomeBusinessLogic(\"" + s + "\")"); 
    count++; 
} 
System.out.println("count = " + count); 

输出

doSomeBusinessLogic("Thisis a test") 
doSomeBusinessLogic("Thisisa test") 
doSomeBusinessLogic("Thisisatest") 
count = 3 

首先,参数replaceFirst()是一个正则表达式,所以你需要躲避参数,所以正则表达式的特殊字符如.,?,*, [, {,...都是tre字面意思,而不是正则表达式模式。要做到这一点,请致电Pattern.quote()

然后,为了提高代码的,所以你不扫描文本两次(和replaceFirst()),并继续从你身在何处扫描,而不是从一开始,用一个变型为标准appendReplacement()循环:

String s = "This is a test"; 
String substr = " "; 

int count = 0; 
StringBuffer buf = new StringBuffer(); 
Matcher m = Pattern.compile(Pattern.quote(substr)).matcher(s); 
while (m.find()) { 
    m.appendReplacement(buf, ""); 
    String ss = buf + s.substring(m.end()); 
    System.out.println("doSomeBusinessLogic(\"" + ss + "\")"); 
    count++; 
} 
// not needed here, but loop usually ends with: m.appendTail(buf); 
System.out.println("count = " + count); 

输出与以前相同。


仅供参考,这里是一个比较正常的appendReplacement循环,随count值替换的空间:

int count = 0; 
StringBuffer buf = new StringBuffer(); 
Matcher m = Pattern.compile(" ").matcher("This is a test"); 
while (m.find()) { 
    m.appendReplacement(buf, String.valueOf(count)); 
    count++; 
} 
m.appendTail(buf); 
System.out.println(buf.toString()); // prints: This0is1a2test 
+0

很好的使用'Matcher'。 –

+0

感觉就像在看String类几乎:) – nullpointer

+0

很高兴看到匹配,但测试用例2不工作.. – irobo

相关问题