14. Longest Common Prefix(leetcode)
来源:互联网 发布:mysql -> 编辑:程序博客网 时间:2024/04/29 05:26
ps:其他的解题报告我放在了我的github上,有需要的朋友可以去看下。github:https://github.com/dyljqq/Algorithm
14. Longest Common Prefix
题目:Write a function to find the longest common prefix string amongst an array of strings.
思路:找所有字符串的最大前缀。我刚开始的想法是先找到最短的字符串,然后根据这个字符串长度去找最大前缀。时间复杂度是O(N * l),l表示最短字符串
的长度。后来发现不需要啊,我拿第一个字符串开始找,每次遍历一遍剩余的字符串的起始字符,那么就能获得最大前缀,然后发现时间快乐好多。时间复杂度是
O(l * N),当然这个是最坏的情况,好一点的就会快很多。比如N=2, 然后l = 1等。所以这个方案显然优于我的第一个方案。
代码:
第一种:(4ms)
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if(strs.size() <= 0)
return "";
int flag = 0;
string smallStr = strs[0];
for(int i = 1; i < strs.size(); i++){
if(smallStr.length() < strs[i].length()){
smallStr = strs[i];
flag = i;
}
}
for(int i = 0; i < strs.size(); i++){
if(i == flag)
continue;
string prefix = "";
for(int j = 0; j < smallStr.length(); j++){
if(strs[i][j] != smallStr[j]){
smallStr = prefix;
break;
}
prefix += smallStr[j];
}
}
return smallStr;
}
};
第二种:
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
int n = strs.size();
if(n == 0)return res;
string res;
for(int pos = 0; pos < strs[0].size(); pos++)
{
for(int k = 1; k < n; k++)
{
if(strs[k].size() == pos || strs[k][pos] != strs[0][pos])
return res;
}
res.push_back(strs[0][pos]);
}
return res;
}
};
0 0
- 14. Longest Common Prefix(leetcode)
- Leetcode:14. Longest Common Prefix(JAVA)
- (JAVA)LeetCode-14. Longest Common Prefix
- [leetcode] 14. Longest Common Prefix[leetcode] 14. Longest Common Prefix
- [LeetCode]14.Longest Common Prefix
- LeetCode 14. Longest Common Prefix
- LeetCode --- 14. Longest Common Prefix
- LeetCode 14.Longest Common Prefix
- [Leetcode] 14. Longest Common Prefix
- 【leetcode】14. longest common prefix
- [leetcode] 14.Longest Common Prefix
- [leetcode] 14. Longest Common Prefix
- LeetCode - 14. Longest Common Prefix
- Leetcode-14. Longest Common Prefix
- Leetcode 14. Longest Common Prefix
- 14. Longest Common Prefix LeetCode
- leetcode 14. Longest Common Prefix
- leetcode 14. Longest Common Prefix
- uva757 - - Gone Fishing
- CSS Position属性
- 小试循环
- 给定一个无序数组,找到其中最小的K个数
- 第二周项目3——小试循环(5)
- 14. Longest Common Prefix(leetcode)
- Android 解决65535的限制
- coreboot学习0:二度相逢是初识
- 自考C++程序设计试题2009年10月
- 最少步数
- 《JAVA与模式》之观察者模式
- MySQL索引详解-02
- 2016年2月鼎桥工作记
- 需要排序的最短子数组长度