题目描述:
Given k strings, find the longest common prefix (LCP).
Example
题目思路:
For strings "ABCD"
, "ABEF"
and "ACEF"
, the LCP is "A"
For strings "ABCDEFG"
, "ABCEFG"
and "ABCEFA"
, the LCP is "ABC"
这题我就偷懒啦,先把vector给sort一下,那么最不一样的两个string就是第一个string和最后一个string。那么我就可以直接找这两个string的LCP了。
Mycode(AC = 16ms):
class Solution {
public:
/**
* @param strs: A list of strings
* @return: The longest common prefix
*/
string longestCommonPrefix(vector<string> &strs) {
// write your code here
if (strs.size() == 0) return "";
sort(strs.begin(), strs.end());
string last_str = strs[strs.size() - 1];
string first_str = strs[0];
string LCP = "";
// find LCP of first string and last string
for (int i = 0; i < first_str.size(); i++) {
if (last_str.size() > i && last_str[i] == first_str[i]) {
LCP += last_str[i];
}
else {
break;
}
}
return LCP;
}
};