class Solution: def longestCommonPrefix(self, strs): longest="" for i in range(min([len(s) for s in strs])): yn=[] for s2 in strs: yn.append(s2.startswith(strs[0][:i+1])) if not (False in yn): longest=strs[0][:i+1] return longest
解题思路:
遍历的次数由最短的字符串决定
判断每个字符串是否有同样的前缀
是则把最长前缀设置为当前前缀
最后返回即可
关注我,在Leetcode专栏中查看更多题目的解题思路吧!