思路:求出所有串中最短的长度,让后遍历这个长度内每个串对应位置字符是不是都相等,如果不是,立即跳出。
本题主义==注意一些边界的测试用例:
[]
["a"]
["a","aa"]
代码:
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <math.h>
#include <stdio.h>
using namespace std;
int my_min(int a,int b)
{
return a<b?a:b;
}
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if(strs.size()==0)return "";
int len = INT_MAX;
int ind = -1;
for(int i= 0;i<strs.size();i++)
{
if(len>strs[i].size())
{
len = strs[i].size();
ind = i;
}
}
string res = strs[ind];
for(int i=0;i<len;i++)
{
bool flag = true;
for(int j = 0;j<strs.size();j++)
{
flag = flag && (strs[j][i]==strs[0][i]);
if(flag==false)
return strs[0].substr(0,i);
}
}
return res;
}
};
4ms的速度,效率上没问题