实现 strStr() 函数。
给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串出现的第一个位置(下标从 0 开始)。如果不存在,则返回 -1 。
class Solution {public int strStr(String haystack, String needle) {if (needle == null || needle.length() == 0) return 0;if (haystack == null) return -1;int len1 = haystack.length();int len2 = needle.length();char[] chars = haystack.toCharArray();char[] chars1 = needle.toCharArray();int[] next = new int[len2];int j = -1;next[0] = j;//一定是从1开始for (int i = 1; i < len2; i++) {while (j >= 0 && chars1[i] != chars1[j + 1]) {j = next[j];}if (chars1[i] == chars1[j + 1]) j++;next[i] = j;}int start = -1;for (int i = 0; i < len1; i++) {while (start >= 0 && chars[i] != chars1[start + 1]) {start = next[start];}if (chars[i] == chars1[start + 1]) start++;if (start == len2 - 1) {return i - len2 + 1;}}return -1;}}
