1. 程式人生 > >2018暑假第八題

2018暑假第八題

題目:

實現 strStr() 函式。(python)

給定一個 haystack 字串和一個 needle 字串,在 haystack 字串中找出 needle 字串出現的第一個位置 (從0開始)。如果不存在,則返回  -1

示例 1:

輸入: haystack = "hello", needle = "ll"
輸出: 2

示例 2:

輸入: haystack = "aaaaa", needle = "bba"
輸出: -1

說明:

當 needle 是空字串時,我們應當返回什麼值呢?這是一個在面試中很好的問題。

對於本題而言,當 needle 是空字串時我們應當返回 0 。這與C語言的 strstr() 以及 Java的 indexOf() 定義相符。

題目連結:

https://leetcode-cn.com/problems/implement-strstr/description/

程式碼:

方法一:

class Solution(object):
    def strStr(self, haystack, needle):
        """
        :type haystack: str
        :type needle: str
        :rtype: int
        """
        return haystack.find(needle)

哈哈,開玩笑,雖然也能通過

方法二:

class Solution(object):
    def strStr(self, haystack, needle):
        """
        :type haystack: str
        :type needle: str
        :rtype: int
        """
        if len(needle) == 0 and len(haystack) == 0:
            return 0
        i = 0
        il = 0
        i2 = 0
        for i in range(len(haystack)):
            il = i
            i2 = i
            j = 0
            while i2<len(haystack) and j<len(needle) and haystack[i2] == needle[j]:
                i2 = i2 + 1
                j = j + 1
            if j == len(needle):
                return il
        return -1

emmm,,,超出時間限制,不過只剩了一個測試用例,應該是對的。。。不改了!想不不出來了!