【LeeCode 简单 矩阵】14 最长公共前缀
程序员文章站
2022-07-13 21:58:55
...
想要看更加舒服的排版、更加准时的推送
关注公众号“不太灵光的程序员”
每日八点有干货推送,微信随时解答你的疑问
14 最长公共前缀 python3
字符串
简单
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 “”。
示例 1:
输入: [“flower”,“flow”,“flight”]
输出: “fl”
示例 2:
输入: [“dog”,“racecar”,“car”]
输出: “”
解释: 输入不存在公共前缀。
说明:
所有输入只包含小写字母 a-z 。
from typing import List
# 93%
# 执行用时:36 ms
# 内存消耗:13.7 MB
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
if not strs: return ""
for i in range(1, len(strs[0])+1):
for car in strs:
if strs[0][:i] == car[:i]:
pass
else:
return strs[0][:i - 1]
return strs[0]
if __name__ == "__main__":
s = Solution()
strs = ["flower", "flow", "flight"]
r = s.longestCommonPrefix(strs)
print(r)
strs = ["flower", "flower", "flower"]
r = s.longestCommonPrefix(strs)
print(r)
strs = ["dog", "racecar", "car"]
r = s.longestCommonPrefix(strs)
print(r)
strs = ["a", "b"]
r = s.longestCommonPrefix(strs)
print(r)
strs = ["aa","ab"]
r = s.longestCommonPrefix(strs)
print(r)
strs = ["aaa","aab"]
r = s.longestCommonPrefix(strs)
print(r)
strs = []
r = s.longestCommonPrefix(strs)
print(r)