https://sodaoo.github.io/2017/11/21/LeetCode-14/
https://sodaoo.github.io
来我的网站查看更多 LeetCode 题解
title: LeetCode(14) Longest Common Prefix
date: 2017-11-21 19:39:24
tags: [LeetCode]
Description :
Write a function to find the longest common prefix string amongst an array of strings.
for example:
“abcjkf” , “abcowi” ,”abcR” ,the longest common prefix string is “abc”
if NO common prefix , just return “” .
翻译 : 寻找最长前缀
比如 :strs = [‘abc’,’abccc’,’abcccdbccccc’]
那么 strs 的最长前缀就是 “abc”
容易想到的思路就是:
只需要寻找最短的字符串里的前缀 是否是其他所有字符串的前缀 .
举例 : strs = [‘abc’,’abccc’,’abcccdbccccc’] ,拿 abc 作参考, 依次判断 ‘a’ ,’b’ ,’c’ 是不是其他字符串的前缀 ,如果是 , 那就向后找, 如果不是 , 返回当前下标 index , 说明 当前字符不能匹配所有的字符串.
# AC 的 Python 代码 :
class Solution:
def longestCommonPrefix(self, strs):
# 首先 ,sort排序默认按照字母排序, 更改排序策略, 按字符串长度排序
# 或者写成 : strs.sort(key=len)
strs.sort(key=lambda x:len(x))
shortest = strs[0] # strs[0] 就是最短的字符串 .
# 调用 find 函数
index = self.find(shortest,strs)
return shortest[0:index]
def find(self,shortest,strs):
# 对最短字符串的每个字符的 index ,word 进行遍历
for index ,word in enumerate(shortest):
for i in range(len(strs)):
if word != strs[i][index]:
return index # 不匹配了 ,终止了 .
# (time: 72ms ,beat 30%)
优化策略 : 缺点就是 如果最短的字符串仍然很长的话 ,会比较很多次
.但是好像也没有更好的解决策略了 .
python 还是慢 ,看看人家的 C++ :
static int x=[]() {
std::ios::sync_with_stdio(false);
cin.tie(NULL);
return 0;
}();
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
string prefix = "";
for(int idx=0; strs.size()>0; prefix+=strs[0][idx], idx++)
for(int i=0; i<strs.size(); i++)
if(idx >= strs[i].size() ||(i > 0 && strs[i][idx] != strs[i-1][idx]))
return prefix;
return prefix;
}
};
// (time: 3 ms ,beat 99.8% )