题目:
Write a function to find the longest common prefix string amongst an array of strings.
思路:
首先找出所有字符串的最小长度。然后依次比较前几位在各个字符串中是否相同,若相同,则作为输出结果;否则,停止循环。
代码:
class Solution {
public:
string longestCommonPrefix(vector<string> &strs) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int len = INT_MAX;
for(int i = 0; i < strs.size(); i++)
{
if(strs[i].size() < len)
{
len = strs[i].size();
}
}
if(len == INT_MAX)
{
len = 0;
}
bool same = true;
int i = 0;
for(; i < len; i++)
{
char c = strs[0][i];
for(int j = 1; j < strs.size(); j++)
{
if(c != strs[j][i])
{
same = false;
break;
}
}
if(!same)
{
break;
}
}
int num;
if(!same)
{
num = i;
}
else
{
num = len;
}
string str;
for(int k = 0; k < num; k++)
{
str.push_back(strs[0][k]);
}
return str;
}
};