Implement strStr()

描述

Implement strStr().

Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.

分析

暴力算法的复杂度是 O(m*n),代码如下。更高效的的算法有KMP算法、Boyer-Mooer算法和Rabin-Karp算法。面试中暴力算法足够了,一定要写得没有BUG。

暴力匹配

  1. // Implement strStr()
  2. // 暴力解法,时间复杂度O(N*M),空间复杂度O(1)
  3. class Solution {
  4. public:
  5. int strStr(const string& haystack, const string& needle) {
  6. if (needle.empty()) return 0;
  7. const int N = haystack.size() - needle.size() + 1;
  8. for (int i = 0; i < N; i++) {
  9. int j = i;
  10. int k = 0;
  11. while (j < haystack.size() && k < needle.size() && haystack[j] == needle[k]) {
  12. j++;
  13. k++;
  14. }
  15. if (k == needle.size()) return i;
  16. }
  17. return -1;
  18. }
  19. };

KMP

  1. // Implement strStr()
  2. // KMP,时间复杂度O(N+M),空间复杂度O(M)
  3. class Solution {
  4. public:
  5. int strStr(const string& haystack, const string& needle) {
  6. return kmp(haystack.c_str(), needle.c_str());
  7. }
  8. private:
  9. /*
  10. * @brief 计算部分匹配表,即next数组.
  11. *
  12. * @param[in] pattern 模式串
  13. * @param[out] next next数组
  14. * @return 无
  15. */
  16. static void compute_prefix(const char *pattern, int next[]) {
  17. int i;
  18. int j = -1;
  19. const int m = strlen(pattern);
  20. next[0] = j;
  21. for (i = 1; i < m; i++) {
  22. while (j > -1 && pattern[j + 1] != pattern[i]) j = next[j];
  23. if (pattern[i] == pattern[j + 1]) j++;
  24. next[i] = j;
  25. }
  26. }
  27. /*
  28. * @brief KMP算法.
  29. *
  30. * @param[in] text 文本
  31. * @param[in] pattern 模式串
  32. * @return 成功则返回第一次匹配的位置,失败则返回-1
  33. */
  34. static int kmp(const char *text, const char *pattern) {
  35. int i;
  36. int j = -1;
  37. const int n = strlen(text);
  38. const int m = strlen(pattern);
  39. if (n == 0 && m == 0) return 0; /* "","" */
  40. if (m == 0) return 0; /* "a","" */
  41. int *next = (int*)malloc(sizeof(int) * m);
  42. compute_prefix(pattern, next);
  43. for (i = 0; i < n; i++) {
  44. while (j > -1 && pattern[j + 1] != text[i]) j = next[j];
  45. if (text[i] == pattern[j + 1]) j++;
  46. if (j == m - 1) {
  47. free(next);
  48. return i-j;
  49. }
  50. }
  51. free(next);
  52. return -1;
  53. }
  54. };

相关题目

原文: https://soulmachine.gitbooks.io/algorithm-essentials/content/cpp/string/strstr.html