28. 找出字符串中第一个匹配项的下标

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算法中中最难理解的是前缀表,前缀表中保存的是当前字符位置之前的字符串的最长相等前后缀,如果期匹配到不相等,则回退到最长的相等前缀之后的位置;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值