3.2ImplementstrStr

Notes:
  Implement strStr().
  Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.
 
  Solution: 1. Check in the haystack one by one. If not equal to needle, reset the pointer.(TLE)
  2. Classice KMP solution.
  3. Simplified RK Soluiton. Thanks for [wenyuanhust, wenyuanhust@gmail.com]
  */


class Solution {
public:
    int strStr_1(char *haystack, char *needle) {
        int sLen = strlen(haystack);
        const int tLen = strlen(needle);
        if (tLen == 0) return 0;
        if(haystack==NULL || needle==NULL || sLen==0) return -1;
        int i = 0, j =0;
        while (i < sLen) {
            j = 0;
            int k = i;
            while (j < tLen && haystack[k] == needle[j]) {
                ++k, ++j;
            }
            if (j == tLen) return k - j;
            ++i;
        }
        return -1;
    }
    void getNext(char * T, int next[], int n){
        int i=0, j=-1;
        next[0]=-1;
        while(i<n){
            while(j>-1&&T[j]!=T[i]) j = next[j];
            i++,j++;
            if(T[j]==T[i]) next[i]=next[j];
            else next[i]=j;
        }
    }
    int strStr_2(char *haystack, char *needle) {
        int sLen = strlen(haystack);
        const int tLen = strlen(needle);
        if (tLen == 0) return 0;
        if(haystack==NULL || needle==NULL || sLen==0) return -1;
        
        int next[tLen+1];
        getNext(needle,next,tLen);
        
        int i=0, j=0;
        while(i<sLen){
            while(j>-1&&needle[j]!=haystack[i]) j = next[j];
            i++,j++;
            if(j==tLen){
                return i - j;
            }
        }
        return -1;
    }
    int strStr_3(char *haystack, char *needle) {
        if (needle && *needle == '\0') return 0;
        if (haystack == NULL || needle == NULL || *haystack == '\0') return -1;
        long long fh = 0, fn = 0;
        char *n = needle, *tail = haystack, *head = haystack;
        while (*n) {
            if (*tail == '0') return -1;
            fh += *tail;
            fn += *n;
            ++n, ++tail;
        }
        --tail;
        while (*tail) {
            if (fn == fh) {
                char *pTemp = head,*nTemp = needle;
                while (*nTemp && *nTemp == *pTemp) {
                    ++nTemp; ++pTemp;
                }
                if (*nTemp == '\0') return head - haystack;
            }
            fh -= *head;
            ++tail;
            ++head;
            fh += *tail;
        }
        return -1;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值