這題使用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())來判斷,這樣在極端條件下就會多出很多步驟,導致超時。