Implement strStr()

来源:互联网 发布:淘宝怎么看店家vip 编辑:程序博客网 时间:2024/05/01 05:36

这题使用Two pointer思路,最开始我的思路是正确的,但是提交的时候提示超时,后来改了一下判断的流程:代码如下:

int strStr(string haystack, string needle) {        int index = 0, i = 0;        if(needle.size()==0)            return 0;        if(haystack.size() == 0 && needle.size() !=0)            return -1;        if(haystack.size() < needle.size())            return -1;       for(i=0;i<haystack.size();i++)        {            int j=0;            if(haystack[i] == needle[j])  //首字母相同则继续            {                if(i + needle.size() > haystack.size())                      return -1;                while(j < needle.size())                {                    if(haystack[j + i] == needle[j])                        j++;                    else                        break;                }                if(j == needle.size())                    return i;            }        }        return -1;    }

最初我不是用if(i + needle.size() > haystack.size())来判断,而是用 if(haystack[j + i] == needle[j] && i+j > haystack.size())来判断,这样在极端条件下就会多出很多步骤,导致超时。

0 0
原创粉丝点击