题目:
Write a function to find the longest common prefix string amongst an array of strings.
链接:http://leetcode.com/problems/longest-common-prefix/
一刷:
class Solution(object): def longestCommonPrefix(self, strs): """ :type strs: List[str] :rtype: str """ if not strs: return ‘‘ length = len(strs[0]) common_prefix = [‘‘] chars_at_idx = set() for idx in range(length): for one_string in strs: if len(one_string) <= idx: return ‘‘.join(common_prefix) chars_at_idx.add(one_string[idx]) if len(chars_at_idx) != 1: return ‘‘.join(common_prefix) common_prefix.append(chars_at_idx.pop()) return ‘‘.join(common_prefix)
可以减少中间变量和数据结构的使用:
class Solution(object): def longestCommonPrefix(self, strs): """ :type strs: List[str] :rtype: str """ if not strs: return ‘‘ length = len(strs[0]) for idx in range(length): char = strs[0][idx] for one_string in strs: if len(one_string) <= idx or one_string[idx] != char: return one_string[:idx] return strs[0]
原文:http://www.cnblogs.com/panini/p/5555642.html