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第一次出现的位置
int strStr(char* haystack, char* needle) {
    int i = 0, j = 0;
    int haySize = strlen(haystack);
    int needleSize = strlen(needle);
    if(needleSize == 0)
        return 0;
    while(i <= haySize - needleSize)
    {
        if(*(haystack + i) == *needle)  //找到第一个相同的点
        {
            while(*(needle + j))        //对needle循环
            {
                if(*(haystack + i + j) == *(needle + j))    //如果后面的都相同,继续判断
                    j++;
                else    //不同则跳出
                {
                    j = 0;
                    break;
                }
            }
            if(!*(needle + j))  //如果判断到最后,说明出现的第一次,返回i
                return i;
        }
        i++;
    }
    return -1;
}
  • 这个题目中默认如果needle为空的话,返回0
posted @ 2015-11-02 08:51  dylqt  阅读(134)  评论(0编辑  收藏  举报