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% )