LeetCode 14. Longest Common Prefix
Solution1:
用的暴力遍历,时间复杂度O(n2)O(n2)
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
int n = strs.size();
if (n == 0) return "";
else if (n == 1) return strs[0];
string common_pre = strs[0];
for (int i = 1; i < n; i++) {
if (common_pre.size() == 0) return "";
if (common_pre.size() > strs[i].size())
common_pre.erase(strs[i].size());
for (int j = 0; j < common_pre.size(); j++) {
if (common_pre[j] != strs[i][j]) {
common_pre.erase(j);
break;
}
}
}
return common_pre;
}
};
LeetCode 14题解析
本文介绍了解决LeetCode第14题“最长公共前缀”的一种暴力遍历方法,该方法的时间复杂度为O(n^2),通过逐个比较字符串来找到最长的共同前缀。
828

被折叠的 条评论
为什么被折叠?



