28. Implement strStr(KMP算法)

题目:
Implement strStr().

Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Example 1:

Input: haystack = “hello”, needle = “ll”
Output: 2

Example 2:

Input: haystack = “aaaaa”, needle = “bba”
Output: -1
解析:找给定字符串的起始位置。
方法一:

class Solution {
public:
    int strStr(string haystack, string needle) {
        int i, j;
        for (i = j = 0; i < haystack.size() && j < needle.size();) {
            if (haystack[i] == needle[j]) {
                ++i; ++j;
            } else {
                i -= j - 1; j = 0;
            }
        }
        return j != needle.size() ? -1 : i - j;
    }
};

方法二:KMP算法

class Solution {
public:
    void getNext(vector<int> &next,string ps)
    {
        string p = ps;
        next[0]=-1;
        int j=0;
        int k=-1;//当A串i位置和B串j+1位置值不同时,j+1的下一个移动位置
        while(j<p.length()-1)
        {
            if(k==-1 || p[j] == p[k])
            {
                if(p[++j] == p[++k])
                    next[j] = next[k];
                else
                    next[j]=k;
            }
            else
                k=next[k];
        }
    }
    int strStr(string haystack, string needle) 
    {
        string t = haystack;
        string p = needle;
        if(t.empty()) return p.empty()?0:-1;
        if(p.empty()) return 0;
        int i=0;//主串的位置
        int j=0;//模式串的位置
        vector<int> next(needle.length()+1);
        getNext(next,needle);
        while(i < t.length())
        {
            if(j == -1 || t[i] == p[j])
            {
                i++;
                j++;
            }
            else
                j=next[j];//j到下一指定位置
            if(j == p.length())
            return i-j;
        }
            return -1;
    }
};

注意:特殊情况的判断如果不单独说明会导致程序超时( if(t.empty()) return p.empty()?0:-1; if(p.empty()) return 0;)。
待解决问题:在主程序中为什么把程序修改为如下就不可以了,思索好久不得解,如果有哪位小伙伴看到的话(希望有人可以看到,期待的搓搓手!!)可以帮我解决一下疑惑,感谢!

while(i < t.size() && j < p.size())
        {
            if(j == -1 || t[i] == p[j])
            {
                i++;
                j++;
            }
            else
                j=next[j];//j到下一指定位置
          
        }
        if(j == p.size())
            return i-j;  
        else
            return -1;

逻辑上应该和上一种写法是一样的啊,大写的不服!如果将它写为下面的形式就可以了,why??

int l1=t.size();
int l2=p.size();
 while(i < l1 && j < l2)
            {
                if(j == -1 || t[i] == p[j])
                {
                    i++;
                    j++;
                }
                else
                    j=next[j];//j到下一指定位置
              
            }
            if(j == p.size())
                return i-j;  
            else
                return -1;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值