14. 最长公共前缀
难度简单
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 ""
。
示例 1:
输入:strs = ["flower","flow","flight"] 输出:"fl"
示例 2:
输入:strs = ["dog","racecar","car"] 输出:"" 解释:输入不存在公共前缀。
class Solution: def longestCommonPrefix(self, strs: List[str]) -> str: final_res = '' min_len = min([ len(ss) for ss in strs]) for i in range(min_len): cur = strs[0][i] for ss in strs[1:]: if ss[i] != cur: res = '' return final_res final_res+=cur return final_res
class Solution { public: string longestCommonPrefix(vector<string>& strs) { sort(strs.begin(),strs.end()); string a = strs.back(); string b = strs[0]; int num = min(a.size(),b.size()); int len = 0; int i = 0; while(i < num) { if (a[i]==b[i]) { len++; } else { break; } i++; } return a.substr(0,len); } };