[leetcode]Implement strStr()

一开始写了个KMP算法,大计算量居然超时,后来用最简单的蛮力算法,居然过了。。

class Solution {
public:
    char *strStr(char *haystack, char *needle) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
         
        int hayLen = strlen(haystack);
        int neeLen = strlen(needle);

        for (int i = 0; i <= hayLen - neeLen; i++){
            char *p = haystack + i;
            char *q = needle;

            while(*q != '\0'){
                if (*p == *q){
                    p++;
                    q++;
                }
                else
                    break;
            }

            if (*q == '\0')
                return p - neeLen;
        }
        return NULL;
    }
 };

 

 

 

EOF

你可能感兴趣的:(LeetCode)