python 刷leetcode 題目(8)
阿新 • • 發佈:2019-01-24
28. 實現strStr()
給定一個 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()
程式碼如下: 通過48ms
class Solution: def strStr(self, haystack, needle): """ :type haystack: str :type needle: str :rtype: int """ h = len(haystack) n = len(needle) for i in range(0, (h - n +1)): if haystack[i: i+n] == needle: return i return -1
14. 最長公共字首
編寫一個函式來查詢字串陣列中的最長公共字首。
如果不存在公共字首,返回空字串 ""
。
示例 1:
輸入: ["flower","flow","flight"] 輸出: "fl"
示例 2:
輸入: ["dog","racecar","car"] 輸出: "" 解釋: 輸入不存在公共字首。
說明:
所有輸入只包含小寫字母 a-z
。
程式碼如下: 耗時48ms,通過
互相學習,互相指教class Solution: def longestCommonPrefix(self, strs): """ :type strs: List[str] :rtype: str """ #### python3 中封裝了os.path.commonprefix(strs),基本和這個題的解法是一樣的 if len(strs) == 0: return "" s1 = min(strs) s2 = max(strs) for i, char in enumerate(s1): if char != s2[i]: return s1[:i] return s1