LeetCode: Implement strStr

Title:

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

当用char*的时候的一些操作,不要和string的弄混了.还有

i <= hayLen-neeLen,去除一些循环
class Solution {
public:
    int strStr(char *haystack, char *needle) {
        if (haystack == NULL || needle == NULL)
            return -1;
        int hayLen = strlen(haystack);
        int neeLen = strlen(needle);
        if (neeLen == 0)
            return 0;
        if (hayLen == 0)
            return -1;
        for (int i = 0 ; i <= hayLen-neeLen; i++){
            char *p = haystack+i;
            char *q = needle;
            while (*q != '\0'){
                if (*p != *q)
                    break;
                else{
                    p++;
                    q++;
                }
            }
            if (*q == '\0')
                return i;
        }
        return -1;
    }
};

 

posted on 2015-04-16 09:04  月下之风  阅读(151)  评论(0编辑  收藏  举报

导航