28. 实现 strStr() 函数。
给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串出现的第一个位置(下标从 0 开始)。如果不存在,则返回 -1 。
说明:
当 needle 是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题。
对于本题而言,当 needle 是空字符串时我们应当返回 0 。这与 C 语言的 strstr() 以及 Java 的 indexOf() 定义相符。
示例 1:
输入:haystack = "hello", needle = "ll"
输出:2
示例 2:
输入:haystack = "aaaaa", needle = "bba"
输出:-1
提示:
1 <= haystack.length, needle.length <= 104
haystack 和 needle 仅由小写英文字符组成
通过次数662,558
提交次数1,626,042
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/implement-strstr
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
/**
* 28. 实现 strStr()
* https://leetcode.cn/problems/implement-strstr/
*
* @param haystack 主串
* @param needle 目标串
* @return int
*/
public int strStr3(String haystack, String needle) {
// 前置判断,快速简单比较
int m = haystack.length();
int n = needle.length();
if (n > m) return -1;
if (n == m && !haystack.equals(needle)) return -1;
// 定义一个质数,用于求字符串hash值
int b = 31;
// 定义主串hash数组
int[] shash = new int[haystack.length() + 1];
for (int i = 1; i < shash.length; i++) {
// abcd = a , a*31^1 + b, a*31^2 + b*31^1 + c, a*31^3 + b*31^2 + c*31^1 + d
shash[i] = shash[i - 1] * b + haystack.charAt(i - 1) - 'a';
}
int pow = 1;
int nhashVal = 0;
for (int i = 0; i < needle.length(); i++) {
nhashVal = nhashVal * b + needle.charAt(i) - 'a';
pow *= b;
}
for (int i = n; i <= m; i++) {
// 例:搜索cd ,( a*31^3 + b*31^2 + c*31^1 + d - (a*31^1 + b)*31^2) = c*31^1 + d
if (shash[i] - shash[i - n] * pow == nhashVal
&& haystack.substring(i - n, i).equals(needle)) {
return i - n;
}
}
return -1;
}