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 "".
Example 1:
1 2
Input: ["flower","flow","flight"] Output: "fl"
Example 2:
1 2 3
Input: ["dog","racecar","car"] Output: "" Explanation: There is no common prefix among the input strings.
Note:
All given inputs are in lowercase letters a-z.
分析
题意是有一堆字符串,求这些字符串中的最长公共前缀,可以将第一个字符串作为操作对象,比较第 n 个字符,只要出现一个字符串的第 n 个字符不等于第一个字符串的第 n 个字符,就返回第一个字符串的 0~n-1 子串。
解决方案1(Python)
1 2 3 4 5 6 7 8 9 10 11 12
class Solution: def longestCommonPrefix(self, strs: List[str]) -> str: if not strs: return "" length, count = len(strs[0]), len(strs) for i in range(length): nowCh = strs[0][i] if any(i == len(strs[j]) or strs[j][i] != nowCh for j in range(1, count)): return strs[0][:i] return strs[0]