[leetcode] Implement strStr()

Implement strStr()

没有使用KMP的算法,也Accepted了。

class Solution {
public:
    char *strStr(char *haystack, char *needle) {
        int hayLen=strlen(haystack);
        int needLen=strlen(needle);
        
        for (int i=0; i<=hayLen-needLen; i++) {
            char *p=haystack+i;
            char *q=needle;
            while (*q!='\0') {
                if (*q==*p) {//相等时,同时后移
                    p++;
                    q++;
                }else{//不相等时,p后移
                    break;
                }
            }
            if (*q=='\0') {
                return haystack+i;
            }
        }
        return NULL;
    }
};

上面的时间复杂度为O(M*N),其中M和N分别为haystack和needle的长度,若使用KMP可降为O(M+N).

http://www.cnblogs.com/easonliu/p/3660748.html

你可能感兴趣的:([leetcode] Implement strStr())