【leetcode】 Implement strStr()

问题:

Implement strStr()

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

分析:效率最高的是KMP算法,但是不容易实现,所以先写了一个传统的字符串匹配算法。

解决办法:
//解决办法1:传统字符串匹配算法
//时间复杂度O(nm),空间复杂度O(1)
class Solution {
public:
    int strStr(string haystack, string needle) {
        int i, j;
        for (i = 0, j = 0; i < haystack.size() && j < needle.size(); ) {
           
           if (haystack[i] == needle[j]) {
                ++i; ++j;
           } else {
               i = i - j + 1;
               j = 0;
           }
        }
       
       return j == needle.size() ? i - j : -1;
    }
};

//KMP算法
//时间复杂度O(n+m),空间复杂度O(1)
class Solution {
public:
    int strStr(string haystack, string needle) {
        //要考虑到当needle为""的情况
        if (needle == "") {
            return 0;
        }
        else {
            vector<int>next(needle.size());
            getNext(needle, next);//获取next数组,保存到vector中

            int i = 0, j = 0;
            while(i != haystack.size() && j != needle.size()) {
                if (j == -1 || haystack[i] == needle[j]) {
                ++i; ++j;
                } 
                else {
                    j = next[j];
                }
            }
            return j == needle.size() ? i - j: -1;
        }
    }
    
    void getNext(string p, vector<int> &next) {
        
        next[0] = -1;

        int i = 0, j = -1;
    
        while (i != p.size() - 1) {
        //这里注意,i==0的时候实际上求的是next[1]的值,以此类推
            if (j == -1 || p[i] == p[j]) {
                ++i;
                ++j;
                next[i] = j;
            } else {
                j = next[j];
            }
        }

    }
};




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值