LeetCode 28.Implement strStr()

题目:

Implement strStr().

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

Update (2014-11-02):
The signature of the function had been updated to return the index instead of the pointer. If you still see your function signature returns a char * or String, please click the reload button  to reset your code definition.

分析与解答:

实现strStr函数,当然啦,按理说应该是KMP啊BM啊sunday啊这种算法,想了想还是用sunday算法吧,毕竟杀鸡焉用牛刀,KMP这种东西,懂得原理就好。

sunday算法非常容易理解,而且实现简便,整体的效率也不错。

sunday算法的思想就是:在匹配失败时关注的是文本串中参加匹配的最末位字符的下一位字符。如果该字符没有 在匹配串中出现则直接跳过,即移动步长= 匹配串长度+ 1;否则,同BM算法一样其移动步长=匹配串中最右端的该字符到末尾的距离+1。

class Solution {
public:
    int strStr(char *haystack, char *needle) {
    int hayLen = strlen(haystack), needleLen = strlen(needle);
    if(needleLen > hayLen)
        return -1;
            if(needleLen == 0)
        return 0;
    int index = 0, i = 0;
    while(index < hayLen) {
        for(i = 0; i < needleLen; i++) { //匹配过程
            if(haystack[index + i] != needle[i])
                break;
        }
        if(i == needleLen) //匹配成功
            return index;
        //匹配失败了,确定文本串中参与匹配的字符串最后一位字符的下一个字符是否在匹配串中,以此计算移动距离
        char nextChar = haystack[index + needleLen]; //最后一位字符的下一个
        int j = needleLen;
        while(nextChar != needle[j - 1] && j > 0)
            j--;
        //确定移动距离
        index += needleLen - j + 1;
    }
    return -1;
    }
};


你可能感兴趣的:(String)