[leetcode algorithms]題目14
14. Longest Common Prefix
Write a function to find the longest common prefix string amongest an array of strings.
自己寫的代碼:
取字元串列表的第一個元素s,從s[:1]遍歷到s[:n],利用helper函數查找其他字元串是否包含s[:i],如果不包含則break。運行時間93ms
class Solution: def helper(self, strs, i, s): res = True for str_ in strs: if str_[:i] != s: res = False break return res def longestCommonPrefix(self, strs): s = strs[0] if strs else n = len(s) res = for i in range(1, n+1): si = s[:i] if self.helper(strs, i, si): res = max(res, si, key=len) return res
推薦閱讀:
※007 Reverse Integer[E]
※[leetcode algorithms]題目11
※LeetCode 680. Valid Palindrome II
※10. Regular Expression Matching
※LeetCode 125. Valid Palindrome
TAG:LeetCode |