Q28 Implement strStr()

Implement strStr().

Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Example 1:
Input: haystack = "hello", needle = "ll"
Output: 2
Example 2:
Input: haystack = "aaaaa", needle = "bba"
Output: -1
解題思路:

此題即實(shí)現(xiàn)Python中內(nèi)置函數(shù) find() 的功能。簡(jiǎn)單方法就是逐個(gè)字符比較,當(dāng)匹配失效后,將子串重新移到開始位置,主串回退前面已經(jīng)匹配的n個(gè)字符,然后繼續(xù)比較。時(shí)間復(fù)雜度 O(m*n)

注意點(diǎn):

此題可采用 KMP 算法求解,時(shí)間復(fù)雜度可以降為 O(m+n),后續(xù)補(bǔ)充。

Python實(shí)現(xiàn):
class Solution:
    def strStr(self, haystack, needle):
        """
        :type haystack: str
        :type needle: str
        :rtype: int
        """
        haylen = len(haystack)
        needlen = len(needle)
        if needlen == 0:
            return 0
        if haylen < needlen:
            return -1
        i = 0; j = 0; count = 0;
        while i < haylen:
            if j < needlen and haystack[i] == needle[j]:
                j += 1
                count += 1
            elif count > 0 and haystack[i] != needle[j]:  # needle從頭開始比較
                j = 0  
                i -= count  # 回退count個(gè)字符
                count = 0
            i += 1  
            if count == needlen:
                return i - count
        return -1

a = "ississip"
b = "issip"
c = Solution()
print(c.strStr(a,b))  # 3
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 今天被“18歲”刷屏了,很多人都有共鳴發(fā)出自己18青澀的樣子,不僅僅是懷念那個(gè)年齡很美好,懷念滿臉的膠原蛋白,更多...
    砂糖醬閱讀 823評(píng)論 0 0
  • 晝夜干咳指枯黃,口臭齒褐肺油黑。 癮來自力怎把持,癮去戒止如抽絲。
    曾良知閱讀 202評(píng)論 0 0
  • 秋風(fēng)瑟瑟秋草黃 貪黑起早整天忙 只曉它鄉(xiāng)風(fēng)光美 不見家鄉(xiāng)豐收忙 庭院紅果枝頭掛 沒有時(shí)間去品嘗 一縷秋思寄冷月 濁...
    滄海桑田_bc60閱讀 171評(píng)論 0 1

友情鏈接更多精彩內(nèi)容