首页 > 其他 > 详细

leetcode 28 实现strstr()

时间:2021-03-13 16:52:38      阅读:29      评论:0      收藏:0      [点我收藏+]

暴力算法就不写了,没什么意义,总得来说就是通过寻找首个字符串中与第二个字符串首字符一致的字符,然后进行判断。代码也不贴了

真正重要的是KMP算法,非常巧妙,通过利用已经匹配到的字符来实现,中心思想就是某个字符串的相同的前缀与后缀,具体细节不详细描述了,贴代码

class Solution {
public:
    int strStr(string haystack, string needle) 
    {
        if(haystack.length()<needle.length())
        return -1;  
        else if(needle.length() == 0)
        return 0;
        int* next = new int[needle.length()];
        next[0] = -1;
        for(int i = 1 ; i < needle.length() ; i++)
        {
            int f = next[i-1];
            while(needle[f+1]!=needle[i] && f>=0)
            f = next[f];
            if(needle[f+1] == needle[i])
            next[i] = f+1;
            else 
            next[i] = -1;
        } 
        int i = 0;
        int j = 0;
        while(i<haystack.length())
        {
            if(haystack[i] == needle[j])
            {
                i++;
                j++;
                if(j == needle.length())
                return i-needle.length();
            }
            else
            {
                if(j == 0)
                i++;
                else
                j = next[j-1]+1;
            }                       
        } 
        return -1;          
    }
};

想复习的时候就看看这个:https://www.cnblogs.com/SYCstudio/p/7194315.html

leetcode 28 实现strstr()

原文:https://www.cnblogs.com/zhaohhhh/p/14529231.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!