Leetcode 14. Longest Common Prefix
Description: Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string ""
Link: 14. Longest Common Prefix
Examples:
Example 1: Input: strs = ["flower","flow","flight"] Output: "fl" Example 2: Input: strs = ["dog","racecar","car"] Output: "" Explanation: There is no common prefix among the input strings.
思路:计算得到最短的string的长度,然后在这个长度内遍历每个字母是否common for all strings.
class Solution(object): def longestCommonPrefix(self, strs): """ :type strs: List[str] :rtype: str """ if not strs: return '' min_len = min([len(s) for s in strs]) res = '' for i in range(min_len): if len(set([s[i] for s in strs])) == 1: res += strs[0][i] else: break return res
我们也可以不去计算最短的string长度,而是直接任意选一个string,然后用try, except IndexError 来处理。
class Solution(object): def longestCommonPrefix(self, strs): """ :type strs: List[str] :rtype: str """ if not strs: return '' res = '' for i in range(len(strs[0])): try: if len(set([s[i] for s in strs])) == 1: res += strs[0][i] else: return res except IndexError: return res return res
日期: 2021-04-17