题目描述
Write a function to find the longest common prefix string amongst an array of strings.
代码
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
int n_str=strs.size();
string ans;
if(n_str == 0) return ans;
int shortest_length=strs[0].size();
for(int i=1;i<n_str;++i)
{
if(strs[i].size()<shortest_length)
{
shortest_length = strs[i].size();
}
}
for(int i = 0;i<shortest_length;++i)
{
int flag = 1;
char ch = strs[0][i];
for(int j=1;j<n_str;++j)
{
if(strs[j][i]!=ch)
{
flag = 0;
break;
}
}
if(flag==1)
{
ans.append(1,ch);
}
else
{
break;
}
}
return ans;
}
};