14. Longest Common Prefix
Posted panini
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了14. Longest Common Prefix相关的知识,希望对你有一定的参考价值。
题目:
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]
以上是关于14. Longest Common Prefix的主要内容,如果未能解决你的问题,请参考以下文章
#Leetcode# 14. Longest Common Prefix