Permalink
Switch branches/tags
Nothing to show
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
31 lines (28 sloc) 742 Bytes
problem:
Write a function to find the longest common prefix string amongst an array of strings.
solution:
bool isCommon(vector<string> &strs, int index)
{
char c = strs[0][index];
for(int i = 1; i < strs.size(); i++)
if(strs[i][index] != c)
return false;
return true;
}
string longestCommonPrefix(vector<string> &strs)
{
if(strs.size() == 0)
return "";
if(strs.size() == 1)
return strs[0];
int nLength = 10000;
string s_prefix = "";
for(int i = 0; i < strs.size(); i++)
nLength = min(nLength, (int)strs[i].length()); //string长度值类型是size_type,所以这里一定要转为int
for(int j = 0; j < nLength; j++)
if(isCommon(strs, j))
s_prefix.append(1, strs[0][j]);
else
break;
return s_prefix;
}