【问题标题】:Fast Text Search快速文本搜索
【发布时间】:2015-04-18 04:51:36
【问题描述】:

我编写这段代码是为了在大文本中搜索小文本。到目前为止,它非常缓慢。我该如何优化它?请帮我优化这段代码。

public class St {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) throws IOException {
    // TODO code application logic here
    BufferedReader b1=new BufferedReader(new InputStreamReader(System.in));
    String s=b1.readLine();
    String t=b1.readLine();
    String news = null;
    //double u=t.hashCode();
    //double q=s.hashCode();
    //double x;
    //.out.print(u+"\n"+q);
    int x=t.length();
    int y=s.length();
    for(int i=0;i<y-x-1;i++){



            //news=s.substring(i, i+t.length());
             //x=news.hashCode();


            //System.out.println(news);
        if(t.equals(s.substring(i, i+x))){
           System.out.println(i);
        }
    }

}


}

【问题讨论】:

    标签: java string algorithm optimization


    【解决方案1】:

    您可以选择一种众所周知的算法及其实现来进行这种性质的搜索。

    您的选项包括Knuth Morris PrattBoyer MooreRabin Karp 算法。他们每个人都有自己的复杂性保证,根据您的输入数据,一个可能比另一个更好。

    从易于实施的角度来看,具有不错的滚动散列函数的 Rabin Karp 应该可以提供可接受的性能。提供了一个可靠的实现here

    另一个可能值得探索的非常好的选择是正则表达式。正则表达式引擎很可能实现了一种快速算法来进行这种性质的子字符串匹配。

    【讨论】:

      【解决方案2】:

      虽然有更智能的算法,但如果没有它们,您也可以实现一些重要的改进。只需使用您在 Java 中所拥有的:

      for (int i=hay.indexOf(needle); i!=-1; i=hay.indexOf(needle, i+1) {
          System.out.println(i);
      }
      

      你的算法太慢了,因为你 n 次复制 m 字符只是为了比较它们。这完全避免了复制。虽然实际字符串的复杂度仍然是O(m*n),但它的性能要好得多,因为通常只需要比较几个字符。

      【讨论】:

      • O(m*n) 时间复杂度太大。我需要更准确的方法来做到这一点。
      • @YasasPasindu 您可以使用滚动哈希码,但这是 Anirudh Ramanathan 提到的算法之一。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-14
      • 2012-03-17
      • 2011-07-30
      • 1970-01-01
      • 2010-09-14
      • 2012-10-26
      相关资源
      最近更新 更多