# 最长公共前缀

编写一个函数来查找字符串数组中的最长公共前缀。

如果不存在公共前缀,返回空字符串 ""

 

示例 1:

输入:strs = ["flower","flow","flight"]
输出:
"fl"

示例 2:

输入:strs = ["dog","racecar","car"]
输出:
""
解释:
输入不存在公共前缀。

 

提示:

以下错误的选项是?

## aop ### before ```cpp #include using namespace std; ``` ### after ```cpp int main() { Solution sol; string arr[] = {"flower", "flow", "flight"}; int length1 = sizeof(arr) / sizeof(arr[0]); vector strs(arr, arr + length1); cout << sol.longestCommonPrefix(strs) << endl; return 0; } ``` ## 答案 ```cpp class Solution { public: string longestCommonPrefix(vector &strs) { if (strs.empty()) return ""; if (strs.size() == 1) return strs[0]; sort(strs.begin(), strs.end()); string s1 = strs[0], s2 = strs.back(); for (int i = 0; i < s1.size(); ++i) { if (i == s2.size()) return s1.substr(0, i); } return s1; } }; ``` ## 选项 ### A ```cpp class Solution { public: string longestCommonPrefix(vector &strs) { string ans; int i, j, flag = 0, n = strs.size(); if (n == 0) return ""; for (i = 0; i < strs[0].length(); i++) { char ch = strs[0][i]; for (j = 1; j < n; j++) { if (i >= strs[j].length() || ch != strs[j][i]) { flag = 1; break; } } if (flag) break; if (j == n) { string x; x = ch; ans.append(x); } } return ans; } }; ``` ### B ```cpp class Solution { public: string longestCommonPrefix(vector &strs) { int len; string str, temp; if (strs.size() == 0) return ""; temp = strs[0]; for (int i = 1; i < strs.size(); i++) { str = strs[i]; string p = ""; if (temp.size() < str.size()) len = temp.size(); else len = str.size(); for (int j = 0; j < len; j++) { if (temp[j] == str[j]) { p = p + str[j]; continue; } else break; } temp = p; } return temp; } }; ``` ### C ```cpp class Solution { public: string longestCommonPrefix(vector &strs) { int sLen = strs.size(); if (sLen == 0) return ""; string dst = ""; int minLen = 100; int minIndex = 0; for (int i = 0; i < sLen; ++i) { int len = strs[i].length(); if (len < minLen) { minLen = len; minIndex = i; } } for (int i = 0; i < strs[minIndex].length(); ++i) { set ch; for (auto iter : strs) ch.insert((iter)[i]); int setLens = ch.size(); if (setLens > 1) break; if (setLens == 1) dst += *ch.begin(); } return dst; } }; ```