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.
Note:
All given inputs are in lowercase letters a-z.
题目意思:就是给一个string的vector,然后求最长公共前缀。
解析:我是暴力解决的。直接将第一个string的完全子集保存起来,然后枚举所有的字符串,有一个不满足就直接跳出来。我觉得这个题没啥意思啊。
代码:
class Solution
{
public:
string longestCommonPrefix(vector<string>& strs)
{
if(strs.size()==0) return "";
int ans;
string commonPrefix = "";
bool ok = true;
int size = strs.size();
string pre = "";
pre+=strs[0][0];
vector<string>prefix;
prefix.push_back(pre);
for(int i=1;i<strs[0].size();i++)
{
pre += strs[0][i];
prefix.push_back(pre);
}
int prefix_cnt = 0;
int prefix_size= prefix.size();
for(int i=0;i<prefix_size;i++)
{
ans = i;
string temp = prefix[i];
for(int j = 1;j< size;j++)
{
string s = "";
for(int k=0;k<i+1;k++) s+=strs[j][k];
if(temp!=s)
{
ok = false;
break;
}
}
if(!ok)
{
ans -=1 ;
break;
}
}
if(ans==-1) return commonPrefix;
for(int i=0;i<=ans;i++) commonPrefix.push_back(strs[0][i]);
return commonPrefix;
}
};