题目英文描述:
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 "".
Note:All given inputs are in lowercase letters a-z.
题目中文描述:
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 ""。
说明:
所有输入只包含小写字母 a-z 。
解题思路:
根据字典序找出数组中最小和最大的字符串,最小最大两个字符串的最长公共前缀即为所有字符串的最长公共前缀。
代码:
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if(strs.empty()) return "";
const auto p = minmax_element(strs.begin(),strs.end()); //找出最小和最大字符串
for(int i = 0; i < p.first->size(); ++i){
if(p.first->at(i) != p.second->at(i))
return p.first->substr(0,i);
}
return *p.first;
}
};