LeetCode:14. 最長公共字首(C++)
阿新 • • 發佈:2019-02-19
題目:
編寫一個函式來查詢字串陣列中的最長公共字首。
如果不存在公共字首,返回空字串 ""
。
示例 1:
輸入: ["flower","flow","flight"]
輸出: "fl"
示例 2:
輸入: ["dog","racecar","car"]
輸出: ""
解釋: 輸入不存在公共字首。
說明:
所有輸入只包含小寫字母 a-z
。
解答:
1. 寫了個分治解法:整個陣列的公共字首 = 對(左邊一半的公共字首 & 右邊一半的公共字首)求一次公共字首。
class Solution { public: string longestCommonPrefix(vector<string>& strs) { if (strs.empty()) { return ""; } else if(strs.size() == 1) { return strs[0]; } else { int half = strs.size() / 2; vector<string> frontHalf(strs.begin(), strs.begin() + half); vector<string> backHalf(strs.begin() + half, strs.end()); string front = longestCommonPrefix(frontHalf); string back = longestCommonPrefix(backHalf); string result = ""; for (int i = 0; i < min(front.length(), back.length()); i++) { if (front[i] != back[i]) { break; } result.append(1, front[i]); } return result; } } };
2. 其實簡單粗暴的掃描空間複雜度更低:
class Solution { public: string longestCommonPrefix(vector<string>& strs) { int index = 0; if (strs.empty()) { return ""; } for (int i = 0; i < strs[0].length(); i++) { char current = strs[0][index]; // 對strs[0][i],strs[1][i],strs[2][i]進行比對 for (string str: strs) { /* strs陣列中有一個不存在第i個字元 或者 index處發生失配 (strs[0][index]與str陣列中的其中一個字串的第i位不相等 這裡index一定等於i)*/ if (str.length() == i || current != str[index]) { return str.substr(0, index); } } index++; } //這裡index一定到了最後面還要過去1個 return strs[0].substr(0, index); } };
3. 另一種掃描方式:可以求出前兩個字串的公共字首,然後用這個字首和後面的字串再求一次公共字首……一直做下去,直到遍歷完整個陣列:
class Solution { public: string longestCommonPrefix(vector<string>& strs) { if (strs.empty()) { return ""; } if (strs.size() == 1) { return strs[0]; } string prefix = strs[0]; //更新prefix,即;令prefix與strs[1], strs[2] ... *strs.end()進行比對 for (int i = 1; i < strs.size(); i++) { int lastIndex = min(prefix.length(), strs[i].length()); for (int j = 0; j < lastIndex; j++) { if (prefix[j] != strs[i][j]) { lastIndex = j; break; } } prefix = prefix.substr(0, lastIndex); } return prefix; } };