Longest Common Prefix
Given k strings, find the longest common prefix (LCP).
Example
For strings "ABCD"
, "ABEF"
and "ACEF"
, the LCP is "A"
For strings "ABCDEFG"
, "ABCEFG"
and "ABCEFA"
, the LCP is "ABC"
class Solution {
public:
/**
* @param strs: A list of strings
* @return: The longest common prefix
*/
string longestCommonPrefix(vector<string> &strs) {
// write your code here
if (strs.size() == 0)
return ""; // 这个条件判断非常重要
int compLen = INT_MAX;
for (int i=0; i<strs.size(); i++)
compLen = min((int)strs[i].size(), compLen);
string retStr = "";
for (int j=0; j<compLen; j++)
{
char pivot = strs[0][j];
for (int i=1; i<strs.size(); i++)
{
if (strs[i][j] != pivot)
{
if (j > 0)
{
return strs[i].substr(0, j);
}
else
{
return "";
}
}
}
}
return strs[0].substr(0, compLen);
}
};