LeetCode : Implement strStr()

Implement strStr().

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

在haystack中查找needle第一次出现的位置:

class Solution{
public:
    int strStr(string haystack, string needle) {
        if (needle.length() == 0)
            return 0;
        if (haystack.length() < needle.length())
            return -1;
        for (int i = 0; i<haystack.length(); ++i){
            int j;
            for (j = 0; j<needle.length(); ++j){
                if (haystack[i + j] != needle[j])
                    break;
            }
            if (j == needle.length())
                return i;
        }
        return -1;
    }
};

posted on 2017-04-28 22:57  gechen  阅读(64)  评论(0编辑  收藏  举报

导航