编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 ""
。
输入: ["flower","flow","flight"] 输出: "fl"
方法一:横向扫描
//Python3
class Solution: def longestCommonPrefix(self, strs: List[str]) -> str: if len(strs) == 0: return "" return reduce(self.helper, strs) def helper(self, str1, str2): ans = "" if len(str1) == 0 or len(str2) == 0: return ans n = min(len(str1), len(str2)) for i in range(n): if str1[i] == str2[i]: ans += str1[i] else: break return ans
//Java
class Solution { public String longestCommonPrefix(string[] strs) { if (strs == null || strs.length == 0) { return ""; } String perfix = strs[0]; int count = strs.length; for (int i = 1; i < count; i++) { prefix = longestCommonPrefix(prefix, strs[i]); if (prefix.length() == 0) { break; } } return prefix; } public String longestCommonPrefix(String str1, String str2) { int length = Math.min(str1.length(), str2.length()); int index = 0; while (index < length && str1.charAt(index) == str2.charAt(index)) { index++; } return str1.substring(0, index); } }
//Golang
func longestCommonPrefix(strs []string) string { if len(strs) == 0 { return "" } prefix := strs[0] count := len(strs) for i := 1; I < count; i++ { prefix = lcp(prefix, strs[I]) if len(prefix) == 0 { break } } return prefix } func lcp(str1, str2 string) string { length := min(len(str1), len(str2)) index := 0 for index < length && str1[index] == str2[index] { index++ } return str1[:index] } func min(x, y int) int { if x < y { return x } return y }