[LeetCode] 14. Longest Common Prefix
题目链接:传送门
Description
Write a function to find the longest common prefix string amongst an array of strings.
Solution
题意:
给定一些字符串,求这些字符串的最长公共前缀
思路:
经典的LCP问题,做法也有很多,直接暴力,后缀数组,字典树,字符串hash等等
(1) 直接做(偷懒
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if (strs.size() == 0) return ""; // missed at first
int len = 0;
for (int i = 0; i < strs[0].length(); i++) {
char cur = strs[0][i];
bool flag = true;
for (int j = 1; j < strs.size(); j++) {
if (strs[j].length() <= i || strs[j][i] != cur) {
flag = false;
break;
}
}
if (flag) len++;
else break;
}
return strs[0].substr(0, len);
}
};
补充:
在官方Solution里面看到分治的思路,有点惊讶,确实没往分治这边想
The idea of the algorithm comes from the associative property of LCP operation. We notice that :
, where is the longest common prefix in set of strings ,
以及二分的思路