|NO.Z.00011|——————————|Applications|——|mysql&mariadb&多例項|
阿新 • • 發佈:2022-03-22
題目
編寫一個函式來查詢字串陣列中的最長公共字首。如果不存在公共字首,返回空字串 ""。
示例1:
輸入:strs = ["flower","flow","flight"]
輸出:"fl"
示例2:
輸入:strs = ["dog","racecar","car"]
輸出:""
解釋:輸入不存在公共字首。
解題思路
- 橫向比較
class Solution { public: string longestCommonPrefix(vector<string>& strs) { if (!strs.size()||strs[0]=="") {//如果vector裡沒有東西 return ""; } string prefix=strs[0];//以strs[0]為標準 int count=strs.size();//容器的容量 //對容器裡的字串逐個與prefix即strs[0]比較,得出最大相同的子串,在這個過程中顯然prefix是逐步更新的 for(int i=1;i<count;++i){ prefix=longestCommonPrefix(prefix,strs[i]); //如果更新後prefix為null說明之前得出的最大相同子串與這一步的字串沒有相同的部分,則返回空串(此刻prefix也是空串,所以跳出迴圈再返回同理) if(!prefix.size())break; } return prefix; } string longestCommonPrefix(const string &str1,const string &str2) { int length=min(str1.size(),str2.size()); int index=0; //index用來記錄相等的字串尾下標 while(index<length && str1[index]==str2[index])++index; //返回相等的字串 return str1.substr(0,index); } };
- 縱向比較
class Solution { public: string longestCommonPrefix(vector<string>& strs) { if (!strs.size()||strs[0]=="")return ""; int length=strs[0].size(); //容器裡第一個字串的長度 int count=strs.size(); //容器裡有多少字串 for(int i=0;i<length;i++){//對strs[0]開始逐列比較 char c=strs[0][i]; for(int j=1;j<count;j++){//從strs[1]開始 if(i==strs[j].size()||strs[j][i]!=c)return strs[0].substr(0,i); } } return strs[0]; } };
- 分治法
class Solution { public: string longestCommonPrefix(vector<string>& strs) { if (!strs.size()) { return ""; } else { return longestCommonPrefix(strs, 0, strs.size() - 1); } } string longestCommonPrefix(const vector<string>& strs, int start, int end) { if (start == end) { return strs[start]; } else { int mid = (start + end) / 2; string lcpLeft = longestCommonPrefix(strs, start, mid); string lcpRight = longestCommonPrefix(strs, mid + 1, end); return commonPrefix(lcpLeft, lcpRight); } } string commonPrefix(const string& lcpLeft, const string& lcpRight) { int minLength = min(lcpLeft.size(), lcpRight.size()); for (int i = 0; i < minLength; ++i) { if (lcpLeft[i] != lcpRight[i]) { return lcpLeft.substr(0, i); } } return lcpLeft.substr(0, minLength); } };
- 先排序再比較
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
sort(strs.begin(), strs.end());
string ans;
string fir = strs.front();
string last = strs.back();
for(int i = 0; i<fir.size() && i<last.size(); ++i){
if(fir[i] != last[i]) break;
ans += fir[i];
}
return ans;
}
};