- 思路,先对字符串数组按照字典序排序,再直接求得第一个和最后一个的最长前缀
- 题解力还有很多有趣的思路
#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
using namespace std;
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if(strs.size()==0) return "";
sort(strs.begin(),strs.end());
string sBegin = strs[0];
string sEnd = strs.back();
return longestCommonPrefixOfTwoElem(sBegin,sEnd);
}
string longestCommonPrefixOfTwoElem(string &a,string &b){
string ans = "";
int flag = a.length()<b.length()?a.length():b.length();
for(int i = 0; i < flag; i++)
{
if(a[i]==b[i])
ans+=a[i];
else return ans;
}
return ans;
}
};