[LeetCode 14] Longest Common Prefix
Write a function to find the longest common prefix string amongst an array of strings.
Diffculty
Easy
Similar Problems
Analysis
求所有字符串的最长公共前缀,即数组的所有字符串都包含这个前缀。
分析:
逐个字符比较,时间复杂度为O(N*L), N是字符串个数,L是最长前缀的长度
class Solution {
public:
string longestCommonPrefix(vector &strs) {
int n = strs.size();
string res;
if(n == 0) return res;
for(int pos = 0; pos < (int)strs[0].size(); pos++)// 最长前缀的长度不超过strs[0].size(),逐个字符的比较
{
for(int k = 1; k < n; k++) // strs[0]的第pos个字符分别和strs[1...n-1]的第pos个字符比较
{
if(strs[k].size() == pos || strs[k][pos] != strs[0][pos])
return res;
}
res.push_back(strs[0][pos]);
}
return res;
}
};