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 int strStr(final String haystack, final String needle) {
  5. if (needle.isEmpty()) return 0;
  6. final int N = haystack.length() - needle.length() + 1;
  7. for (int i = 0; i < N; i++) {
  8. int j = i;
  9. int k = 0;
  10. while (j < haystack.length() && k < needle.length() &&
  11. haystack.charAt(j) == needle.charAt(k)) {
  12. j++;
  13. k++;
  14. }
  15. if (k == needle.length()) return i;
  16. }
  17. return -1;
  18. }
  19. }

KMP

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

相关题目

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