题目要求:
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在最长公共前缀,返回空字符串 “”。
示例:
示例 1:
输入: [“flower”,”flow”,”flight”]
输出: “fl”示例 2:
输入: [“dog”,”racecar”,”car”]
输出: “”解释: 输入不存在最长公共前缀。
- 说明:所有输入只包含小写字母 a-z 。
范例代码:
思路:
- 如果strs为空, 返回空字符串;
- 找最长公共前缀, 只需对比max(strs)和min(strs);
- 技巧点: 字符串求最小值, 是根据字符的ASCII码排序的。
# 例1:
min(["hello", 'abc', 'he']) # 结果显示为"abc";
# 例2:
min(['a', 'abc', 'ae']) # 结果显示为"ae"
class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
# 如果strs为空, 返回空字符串;
if not strs: return ''
# 找最长公共前缀, 只需对比最长的字符串和最短字符串;
s1 = min(strs)
s2 = max(strs)
for i, c in enumerate(s1):
if c != s2[i]:
return s1[:i]
return s1
最最最简洁的办法
import os
class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
# 直接调用已经完成并实现的方法;
return os.path.commonprefix(strs)