一、问题描述
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: strs = ["flower","flow","flight"]
Output: "fl"
Example 2:
input: strs = ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
二、代码
思路:
1、选取字符串中的一个元素(第一个元素)为基准,遍历基准的字符,并与字符串中的其他元素的相应位置比较。时间复杂度为O(nlogm)。
2、按照字典序(ascii码)对字符串进行排序,然后寻找最大值和最小值的公共前缀。
C++:
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if(strs.empty())
{
return "";
}
int length = strs[0].size();
int count = strs.size();
for (int i = 0; i < length ; i++)
{
char c = strs[0][i];
for(int j = 1;j < count ;j++)
{
if(i == strs[j].size() || c != strs[j][i])
{
return strs[0].substr(0,i); //切割函数
}
}
}
return strs[0];
}
};
python:
class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if not strs: return ""
s1 = min(strs)
s2 = max(strs)
for i,x in enumerate(s1):
if x != s2[i]:
return s2[:i]
return s1