- 思路,先对字符串数组按照字典序排序,再直接求得第一个和最后一个的最长前缀
- 题解力还有很多有趣的思路
- 水平扫描法
- 分治法
- 二分法
#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
// 求最长公共前缀
//思路,先对字符串数组按照字典序排序,再直接求得第一个和最后一个的最长前缀
using namespace std;
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
// 先对strs字典序排序
if(strs.size()==0) return "";
sort(strs.begin(),strs.end());
string sBegin = strs[0];
string sEnd = strs.back();
// cout<<sBegin<<endl<<sEnd;
// 求sBegin和sEnd的最长前缀
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;
}
};
版权声明:本文为weixin_38494588原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。