方法有点蠢,没想好怎么不用循环取所有元素的前index位,就顺手这么写了。
Success
Details Runtime: 32 ms, faster than 99.37% of Python3 online submissions forLongest Common Prefix.
Memory Usage: 13.2 MB, less than 36.85% of Python3 online submissions for Longest Common Prefix.
Submission Detail
118 / 118 test cases passed.
|
Status:
Accepted |
Runtime: 32 ms
Memory Usage: 13.2 MB
|
Submitted: 2 minutes ago
|
class Solution: def longestCommonPrefix(self, strs: List[str]) -> str: times = 0 for index in range(len(strs)): if len(strs[index]) > times: times = len(strs[index]) #circle for (times) times ret ='' for index in range(times): isequal = True temp = strs[0][:index+1] for i in range(1,len(strs)): if temp == strs[i][:index+1]: pass else: isequal = False break if isequal: ret = temp else: break return ret
国际惯例抄一个:
class Solution: def longestCommonPrefix(self, strs: List[str]) -> str: if '' in strs or not strs: return '' index = 0 for i, item in enumerate(zip(*strs)): if len(set(item)) != 1: return strs[0][:i] else: index = i return strs[0][:index + 1]