标签:pytho span ascii not self def 一个 rac 对齐
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 ""。
示例 1:
输入: ["flower","flow","flight"]
输出: "fl"
示例 2:
输入: ["dog","racecar","car"]
输出: ""
解释: 输入不存在公共前缀。
说明:
所有输入只包含小写字母 a-z 。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-common-prefix
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
python解法:
因为python中有max,min可以比较字符串ascii的大小,可以直接找到max和min字符串,对比它们的公共前缀,即为最长公共前缀。max的前缀后一位存在且比min大,所以在min中找前缀。
1 class Solution: 2 def longestCommonPrefix(self, strs: List[str]) -> str: 3 if not strs : return "" 4 s1=max(strs) 5 s2=min(strs) 6 for i,x in enumerate(s2): 7 if x != s1[i]: 8 return s1[:i] 9 return s2
1 def longestCommonPrefix(self, strs): 2 if not strs: return "" 3 ss = list(map(set, zip(*strs))) 4 res = "" 5 for i, x in enumerate(ss): 6 x = list(x) 7 if len(x) > 1: 8 break 9 res = res + x[0] 10 return res
标签:pytho span ascii not self def 一个 rac 对齐
原文地址:https://www.cnblogs.com/zccfrancis/p/12185300.html