Implement strStr() - (第一子串位置)

Implement strStr().

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

Input: haystack = "hello", needle = "ll"
Output: 2

Input: haystack = "aaaaa", needle = "bba"
Output: -1

class Solution:
    def strStr(self, haystack, needle):
        """
        :type haystack: str
        :type needle: str
        :rtype: int
        """
        if not needle:
            return 0
        index = 0
        n = len(needle)
        i = 0
        while i < len(haystack):
            if haystack[i] == needle[index]:
                index += 1
                i += 1
                if index == n:
                    return i - n 
            else:
                i = i - index + 1
                index = 0
        return -1
class Solution:
    def strStr(self, haystack, needle):
        """
        :type haystack: str
        :type needle: str
        :rtype: int
        """
        return haystack.find(needle)

?著作權(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)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

  • 葉絡(luò)陷入玄之又玄的修煉境界之中,轉(zhuǎn)眼已過(guò)了億年,混沌元?dú)庠诓粩嗟南蛳忍煸獨(dú)廪D(zhuǎn)化之中,整個(gè)洪荒大地殘余的混沌之氣...
    葉絡(luò)閱讀 272評(píng)論 0 0
  • 今天秋葉大叔在微信上提出了一個(gè)特別的書(shū)評(píng),就是《躍遷》的七問(wèn)。 【1】問(wèn)題一:今天你是如何讀書(shū)的? 過(guò)去2000年...
    仗踐走天涯閱讀 344評(píng)論 0 0
  • 最初的問(wèn)題是邏輯回歸相對(duì)于決策樹(shù)有哪些優(yōu)勢(shì),什么場(chǎng)景下邏輯回歸比決策樹(shù)效果更好。大多數(shù)情況下,“Should I ...
    cae6f12ddc62閱讀 5,246評(píng)論 0 3
  • 有一種體會(huì)是 無(wú)意間聽(tīng)到那首為愛(ài)癡狂 熟悉的旋律飄進(jìn)心底 一瞬間又不爭(zhēng)氣的濕了眼眶 然后笑著悲傷 發(fā)生在意料之外的...
    人生且呵呵閱讀 212評(píng)論 0 0

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