Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string ""
.
Example 1:
Input: ["flower","flow","flight"] Output: "fl"
Example 2:
Input: ["dog","racecar","car"] Output: "" Explanation: There is no common prefix among the input strings.
题目翻译:
一个vector<string> vec里边存了很多string,求这些string的最大相同的头部分。
很简单的题目,从头依次遍历即可,如果vec是空的,返回空,如果vec是1,则直接把结果返回,如果vec>=2,继续查找公共最大的范围。
#include<iostream>
#include<cmath>
#include<string>
#include<vector>
using namespace std;
class Solution{
public:
string longestCommonPrefix(vector<string> &vec)
{
string str="";
int n=vec.size();
if(n==0)
return str;
if(n==1)
{
str=vec[0];
return str;
}
int count=0;
int istrue=0;
int max=vec[0].length();
while(count<max)
{
char temp=vec[0][count];
for(int i=1;i<n;i++)
{
if(temp!=vec[i][count])
istrue=1;
}
if(istrue==1)
break;
else
count++;
}
for(int i=0;i<count;i++)
str+=vec[0][i];
return str;
}
};
int main()
{
vector<string> vec;
vec.push_back("flower");
vec.push_back("flow");
vec.push_back("flight");
Solution so;
string str=so.longestCommonPrefix(vec);
cout<<str<<endl;
system("pause");
return 0;
}