LeetCode 28 [Implement strStr()]

原題

字符串查找(又稱查找子字符串),是字符串操作中一個很有用的函數(shù)。你的任務是實現(xiàn)這個函數(shù)。
對于一個給定的 source 字符串和一個 target 字符串,你應該在 source 字符串中找出 target 字符串出現(xiàn)的第一個位置(從0開始)。
如果不存在,則返回 -1。

如果 source = "source" 和 target = "target",返回 -1。
如果 source = "abcdabcdefg" 和 target = "bcd",返回 1。

解題思路

  • 雙層for循環(huán), O(m*n)
  • 注意一些邊界情況,主要是開頭的處理
  • haystack == None , needle == None 要返回-1
  • haystack == "" , needle == "" 要返回0而不是-1
  • needle = "" 要返回0

完整代碼

class Solution(object):
    def strStr(self, haystack, needle):
        """
        :type haystack: str
        :type needle: str
        :rtype: int
        """
        if haystack == None or needle == None or len(haystack) < len(needle):
            return -1
        if haystack == needle or needle == "":
            return 0
        for i in range(len(haystack) - len(needle) + 1):
            flag = True
            res = i
            for char in needle:
                if char == haystack[i]:
                    i += 1
                else:
                    flag = False
            if flag:
                return res
        return -1
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容