实现 strStr() 函数。

给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串出现的第一个位置(下标从 0 开始)。如果不存在,则返回 -1 。

  1. class Solution {
  2. public int strStr(String haystack, String needle) {
  3. if (needle == null || needle.length() == 0) return 0;
  4. if (haystack == null) return -1;
  5. int len1 = haystack.length();
  6. int len2 = needle.length();
  7. char[] chars = haystack.toCharArray();
  8. char[] chars1 = needle.toCharArray();
  9. int[] next = new int[len2];
  10. int j = -1;
  11. next[0] = j;
  12. //一定是从1开始
  13. for (int i = 1; i < len2; i++) {
  14. while (j >= 0 && chars1[i] != chars1[j + 1]) {
  15. j = next[j];
  16. }
  17. if (chars1[i] == chars1[j + 1]) j++;
  18. next[i] = j;
  19. }
  20. int start = -1;
  21. for (int i = 0; i < len1; i++) {
  22. while (start >= 0 && chars[i] != chars1[start + 1]) {
  23. start = next[start];
  24. }
  25. if (chars[i] == chars1[start + 1]) start++;
  26. if (start == len2 - 1) {
  27. return i - len2 + 1;
  28. }
  29. }
  30. return -1;
  31. }
  32. }

参考文献

  1. 实现 strStr()