题目:
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:
Input: [“flower”,“flow”,“flight”]
Output: “fl”
Example 2:
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.
方法1:
纵向遍历 以第一个字符串为基准 依次比较各个字符串 如果字符相等则继续 否则说明已经找到公共前缀,注意要防止索引越界
c++:
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if(strs.empty()) return "";
for(int j = 0; j < strs[0].size(); j++){
for(int i = 1; i < strs.size(); i++){
if(j >= strs[i].size() || strs[i][j] != strs[0][j]){
return strs[0].substr(0, j);
}
}
}
return strs[0];
}
};
java:
- 数组是length 而 字符串是length()
- isEmpty() 函数用于ArrayList,HashSet,HashMap和String
- 判断为空还要考虑空指针
class Solution {
public String longestCommonPrefix(String[] strs) {
if(strs == null || strs.length == 0) return "";
for(int j = 0; j < strs[0].length(); j++){
for(int i = 1; i < strs.length; i++){
if(j >= strs[i].length() || strs[i].charAt(j) != strs[0].charAt(j)){
return strs[0].substring(0, j);
}
}
}
return strs[0];
}
}
Python:
zip函数对应的元素打包成一个个元组,然后返回由这些元组组成的列表
zip(*strs)将对应的字符串字符打包,而zip(strs)打包整个字符串
set函数 排除重复元素
class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if not strs: return ''
l = 0
for cg in zip(*strs):
if len(set(cg)) > 1:
return strs[0][:l]
l += 1
return strs[0][:l]
方法2:
对字符串排序,这样拥有最少匹配的字符串将在首尾的位置,接着只需比较首尾字符串
c++:
back和front函数指向vector的尾部和首部元素
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if(strs.empty()) return "";
sort(strs.begin(), strs.end());
int n = min(strs[0].size(), strs.back().size());
for(int i = 0; i < n; i++){
if(strs[0][i] != strs.back()[i]) return strs[0].substr(0, i);
}
return strs[0];
}
};
java:
排序:Arrays.sort(strs);
class Solution {
public String longestCommonPrefix(String[] strs) {
if(strs == null || strs.length == 0) return "";
Arrays.sort(strs);
int n = Math.min(strs[0].length(), strs[strs.length - 1].length());
for(int i = 0; i < n; i++){
if(strs[0].charAt(i) != strs[strs.length - 1].charAt(i)) return strs[0].substring(0, i);
}
return strs[0];
}
}
python:
排序:strs.sort()
class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if not strs: return ''
strs.sort()
n = min(len(strs[0]), len(strs[-1]))
i = 0
while i < n and strs[0][i] == strs[-1][i]:
i += 1
return strs[0][:i]