https://leetcode.cn/problems/find-the-index-of-the-first-occurrence-in-a-string/
题目要求
给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串的第一个匹配项的下标(下标从 0 开始)。如果 needle 不是 haystack 的一部分,则返回 -1 。
滑动窗口
public int strStr(String haystack, String needle) {
int m = needle.length();
if (m == 0) return 0;
int n = haystack.length();
if (n < m) return -1;
int i = 0, j = 0;
while (i < n - m + 1) {
// 找到首字母相等的位置
while (i < n && haystack.charAt(i) != needle.charAt(j)) i++;
// 没有首字母相等的
if (i == n) return -1;
j++;
i++;
while (i < n && j < m && haystack.charAt(i) == needle.charAt(j)) {
i++;
j++;
}
if (j == m) return i - j;
else {
i -= j - 1;
j = 0;
}
}
return -1;
}
KMP
class Solution {
public int strStr(String haystack, String needle) {
if (needle.length() == 0) return 0;
int[] next = new int[needle.length()];
getNext(next, needle);
int n = haystack.length(), m = needle.length();
int j = 0;
for (int i = 0; i < n; i++) {
// 比较不相等,回退
while (j > 0 && haystack.charAt(i) != needle.charAt(j))
j = next[j - 1];
// 相等,继续比较
if (haystack.charAt(i) == needle.charAt(j))
j++;
if (j == m)
return i - j + 1;
}
return -1;
}
public void getNext(int[] next, String s) {
int j = 0;
next[0] = 0;// 初始化
for (int i = 1; i < s.length(); i++) {
while (j > 0 && s.charAt(j) != s.charAt(i))// 前后缀比较的这一位不相同
j = next[j - 1];// 向前回退
if (s.charAt(j) == s.charAt(i))// 找到相同的前后缀
j++;
next[i] = j;// 将前缀的长度赋给next[i]
}
}
}
思路
- 滑动窗口的思想就是找到有相同的循环进行比较,如果比较完成都相等则返回
true
。 - KMP算法中中最难理解的是前缀表,前缀表中保存的是当前字符位置之前的字符串的最长相等前后缀,如果期匹配到不相等,则回退到最长的相等前缀之后的位置;