algorithm - 子字符串在字符串中出现的性能

标签 algorithm performance string search

我遇到了在另一个字符串中查找子字符串的所有出现的任务,并且想知道解决这个问题的最佳算法是什么。

出于演示目的,我使用了字符串“The cat sat on the mat”并搜索所有出现的子字符串“at”。这最终应该导致出现次数为 3。因为我现在正在用 Java 编程,所以我首先想到的是:

    public static void main(String[] args) {

      int count=0;
      String s = "The cat sat on the mat";

      Pattern pattern = Pattern.compile("at");
      Matcher matcher = pattern.matcher(s);
      while(matcher.find()){
          count++;
      }

      System.out.println("Pattern: "+pattern+" Count: "+count);
    }

不知何故,我怀疑这是解决此问题的最佳解决方案。因此,如果有人知道最佳(或至少相当不错)的解决方案应该是什么样子……请回答!您可以使用任何语言发布您的答案,不一定是 java(尽管那会很棒 :))。

非常感谢!

最佳答案

有很多令人印象深刻的子串算法。通常提到 Boyer-Moore 算法 ( http://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_string_search_algorithm ),但还有其他替代方案,例如 http://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithmhttp://en.wikipedia.org/wiki/Rabin-karp .

关于algorithm - 子字符串在字符串中出现的性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3582939/

相关文章:

java - 合并步骤后的一些更大的元素不在枢轴的右侧

java - Java 中循环的性能

string - 最长回文子串和后缀 trie

java - 更好的数据结构,可以更快地读取 Map of Map of Map of Lists

python - 使用 str() 将字节转换为字符串返回带有语音标记的字符串

string - 从字符串中删除空格

algorithm - 整个算法的时间复杂度是多少?

比较所有数组元素——C算法

c - 中止陷阱 : 6 with loop in c

java - 该算法的时间和空间复杂度是多少?