【leetcode】Implement strStr() (easy)

Implement strStr().

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

 

思路:

注意,在for循环中条件有计算得到的负数时, 一定要把计算括起来转换为int, 否则会默认转换为uchar 负数就会被误认为是一个很大的数字。

for(int i = 0; i < int(1 - 2); ++i)

 

实现很常规:

int strStr(string haystack, string needle) {
        for(int i = 0; i <= int(haystack.size() - needle.size()); ++i)
        {
            int j;
            for(j = 0; j < needle.size() && haystack[i + j] == needle[j]; ++j);
            if(j == needle.size())
                return i;
        }
        return -1;
    }

 

posted @ 2015-05-22 22:48  匡子语  阅读(130)  评论(0编辑  收藏  举报