[LeetCode] Implement strStr() 字符串子串

Question:

Implement strStr().
Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.

Solution (C++):

class Solution {
public:
    char *strStr(char *haystack, char *needle) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        int len_needle = strlen(needle);
        int len_haystack = strlen(haystack);
        
        if(len_needle == 0) return haystack;
        if(len_needle > len_haystack) return NULL;
        
        char *s1;
        char *s2 = needle;
        char *cp = haystack;
        char *s1Adv = haystack;
        while(*++s2) {
            s1Adv++;
        }
        
        while(*s1Adv)
        {
            s1 = cp;
            s2 = needle;
            while(*s1 && *s2 && *s1 == *s2)
            {
                s1++; 
                s2++;
            }
            if(!*s2) return cp;
            cp++;
            s1Adv++;
        }
        return NULL;
    }
};


以上是比较straight-forward的实现方式,也可以用经典高效的KMP算法实现:

class Solution {
public:
    void compute_prefix(char* T, int m, vector<int>& pi) {
        int i = 0;
        int j = pi[0] = -1;
        while (i < m) {
            while (j > -1 && T[i] != T[j]) {
                j = pi[j];
            }
            ++i;
            ++j;
            pi[i] = (T[i] == T[j]) ? (pi[j]) : (j);
        }
    }

    char *strStr(char *haystack, char *needle) {
        int n = strlen(haystack);
        int m = strlen(needle);
        if (m == 0) {
            return haystack;
        }

        vector<int> pi(m+1);
        compute_prefix(needle, m, pi);

        int i = 0;
        int j = 0;
        while (i < n) {
            while (j > -1 && haystack[i] != needle[j]) {
                j = pi[j];
            }
            ++i;
            ++j;
            if (j >= m) {
                return haystack+i-j;
            }
        }
        return 0;
    }
};

                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值