[leetcode]28. Implement strStr()

来源:互联网 发布:淘宝企业店铺能贷款吗 编辑:程序博客网 时间:2024/06/03 16:31

实现strStr(),返回needle在haystack中第一次出现的索引号,如果没有找到输出-1

第一次pass 73/74,根据提醒,如果haystack="a"  needle=" " 默认空和任何数都是匹配的。

我写的时间复杂度有些大,是O(n2)

 

class Solution {public:    int strStr(string haystack, string needle) {        int size1 = haystack.size();        int size2 = needle.size();        if(size1 < size2)            return -1;        if(needle=="")            return 0;        for(int i=0; i<=(size1-size2); i++)        {            if(haystack[i] == needle[0])            {                int flag = 1;                int j=1;                while( (flag==1) &&(j<size2) )                {                    if(haystack[i+j]!=needle[j])                        flag = 0;                    j++;                }                if(flag==1)  return i;            }        }        return -1;    }};

0 0