美文网首页
28. Implement strStr()

28. Implement strStr()

作者: i_Eloise | 来源:发表于2018-01-22 08:53 被阅读0次
class Solution {
public:
    int strStr(string haystack, string needle) {
        if(needle.size()==0)
            return 0;
        if(needle.size()>haystack.size())
            return -1;
        if(haystack.size()==needle.size())
        {
            if( haystack.compare(needle)==0)
                return 0;
            else
                return -1;
        }
        int index = 0;
        int i;
        for(i = 0 ; i < haystack.size()-needle.size()+1;i++)
        {
            if(haystack[i]==needle[0])
            {
                index = i;
                int j = 1;
                while(j < needle.size())
                {
                    if(haystack[i+j]==needle[j])
                        j++;
                    else
                        break;
                }
                if(j == needle.size())
                    return index;
            }
        }
        if(i == haystack.size()-needle.size()+1)
            return -1;
    }
};

易错点:
if(needle.size()==0)
return 0;

相关文章

网友评论

      本文标题:28. Implement strStr()

      本文链接:https://www.haomeiwen.com/subject/pznkaxtx.html