Implement strStr()

這題使用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())來判斷,這樣在極端條件下就會多出很多步驟,導致超時。
發佈了50 篇原創文章 · 獲贊 7 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章