TypechoJoeTheme

Toasobi的博客

KMP算法--找出字符串中第一个匹配的下标

本文最后更新于2023年09月14日,已超过371天没有更新。如果文章内容或图片资源失效,请留言反馈,我会及时处理,谢谢!

这道题需要学习的是KMP算法

public int strStr(String haystack, String needle) {
        if (needle.isEmpty()) return 0;

        char[] s = haystack.toCharArray();
        char[] p = needle.toCharArray();

        int m = needle.length();
        int n = haystack.length();

        int[] next = new int[m];

        //构建next数组
        next[0] = -1;
        int i = 0;
        int j = -1;
        while(i < m - 1){
            if(j == -1 || p[i] == p[j]){
                next[++i] = ++j;
            }else{
                j = next[j];
            }
        }

        i = 0;
        j = 0;  
        while(i < n && j < m){
            if(j == -1 || s[i] == p[j]){
                i++;
                j++;
            }else{
                j = next[j];
            }
            if(j == m){
                return i-j;
            }
        }
        return -1;
    }

KMP算法虽难,但是背会了它就相当与掌握一个api

朗读
赞(0)
评论 (0)