Longest Common Prefix
题目:
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
*/
string longestCommonPrefix(vector<string> &strs) {
// write your code here
if (strs.size() == 0) {
return "";
}
int minLength = INT_MAX;
for (int i = 0; i < strs.size(); i++) {
if (minLength > strs[i].size() ) {
minLength = strs[i].size();
}
}
string res = "";
for (int i = 0; i < minLength; i++) {
char curr = strs[0][i];
for (int j = 0; j < strs.size(); j++) {
if (strs[j][i] != curr) {
return res;
}
}
res += curr;
}
return res;
}
};