最長公共長度
題目: 撰寫一個函式來查找字串陣列中的最長公共前綴,
如果不存在公共前綴,回傳空字串
"",
說明:
所有輸入只包含小寫字母 a-z ,
思路:
- 先考慮兩個字串最長公共長度
- 然后保存相同最長公共長度字串再與后面字串比較
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if(!strs.size()) return "";
string str = strs[0];
int count = strs.size();
for(int i = 1; i < count; ++i){
str = longestCommonPrefix(str, strs[i]);
if(str == ""){
break;
}
}
return str;
}
string longestCommonPrefix(const string& str1, const string& str2){
int len = min(str1.size(), str2.size());
int index = 0;
for(int i = 0; i < len; ++i){
while(index < len && str1[index] == str2[index]){
index++;
}
}
return str1.substr(0, index);
}
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/243231.html
標籤:其他
上一篇:資料結構與演算法 基礎實驗
