78. Longest Common Prefix【medium】

时间:2023-03-09 20:30:00
78. Longest Common Prefix【medium】

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"

解法一:

 class Solution {
public:
/**
* @param strs: A list of strings
* @return: The longest common prefix
*/
int min(int a, int b) {
return ((a < b) ? a : b);
} int calCount(string & a, string & b) {
int la = a.size();
int lb = b.size();
int count = ; for (int i = ; i < la && i < lb; ++i) {
if (a[i] == b[i]) {
count++;
} else {
return count;
}
}
} string longestCommonPrefix(vector<string> &strs) {
int count = INT_MAX;
int size = strs.size(); if (size == ) {
return "";
} for (int i = ; i < strs.size() - ; ++i) {
count = min(calCount(strs[i], strs[i + ]), count);
} return strs[].substr(, count);
}
};

解法二:

 class Solution {
public:
/**
* @param strs: A list of strings
* @return: The longest common prefix
*/
string longestCommonPrefix(vector<string> &strs) {
if (strs.size() == ) {
return "";
} string prefix = "";
for (int i = ; i < strs[].length(); i++) {
for (int j = ; j < strs.size(); j++) {
if (strs[j][i] != strs[][i]) {
return prefix;
}
}
prefix += strs[][i];
} return prefix;
}
};