leetcode 14 Longest Common Prefix

简介: Write a function to find the longest common prefix string amongst an array of strings. 我的解决方案: class Solution {public: string longes...

Write a function to find the longest common prefix string amongst an array of strings.



我的解决方案:

class Solution {
public:
    string longestCommonPrefix(vector<string>& strs)
    {
        
        if(strs.size() == 0) 
        return "";
        
        sort(strs.begin(),strs.end());
        int size = strs.size();
        int min_size = strs[0].length();
        string prefix = "";
        for(int i =0;i< min_size;++i)
        {
            char temp = strs[0][i];
            for(int j = 1;j<size;++j)
            {
                if(strs[j][i]!=temp)
                {
                    //break;
                    return prefix;
                }
                
            }
            prefix.append(1,temp); //= prefix +temp;//const char*的话怎么加进去呢?
        }
        
        return prefix;
    }
};



c++解决方案:

class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
        if(strs.empty()) return "";
        std::sort(strs.begin(),strs.end());
        string ans=strs[0];
        for (int i = 0; i < strs.size(); ++i)       
            for (int j = 0; j < ans.length() ; ++j)
            {
                if(ans[j]!=strs[i][j]) { 
                    ans=ans.substr(0,j);
                    break;
                } 
            }
        return ans;

};

//But when I changed the first loop initial value "int i=1",it cost 8ms. As it is easy to proof the i=0 don't need to compare. //The loop less one time,but cost more than 4ms.



	string longestCommonPrefix(vector<string>& strs) {
    if(strs.size() == 0) 
        return "";

    string result;
    for(int i = 0; i<strs[0].length(); i++) {
        char c = strs[0][i];
        for(int j = 0; j<strs.size(); j++) {
            if(strs[j][i] != c)
                return result;
        }

        result += c;
    }

    return result;
}



//Divide-and-Conquer Approach, python, 44ms 
 



   
		
class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
        if (strs.empty()) return "";
        for (int pos = 0; pos < strs[0].length(); pos++)
            for (int i = 1; i < strs.size(); i++)
                if (pos >= strs[i].length() || strs[i][pos] != strs[0][pos])
                    return strs[0].substr(0, pos);
        return strs[0];
    }
};


class Solution {
public:
    string longestCommonPrefix(vector<string> &strs) {
        int i, j, n = strs.size();
        if (n == 0) return "";
        sort(strs.begin() ,strs.begin() + n);
        for (j = 0; j < strs[0].size() && j < strs[n - 1].size() && strs[0][j] == strs[n - 1][j]; j++);
        return strs[0].substr(0, j);
    }
};





python解决方案:


class Solution:
    # @return a string
    def longestCommonPrefix(self, strs):
        if not strs:
            return ""

        for i, letter_group in enumerate(zip(*strs)):
            if len(set(letter_group)) > 1:
                return strs[0][:i]
        else:
            return min(strs)


def longestCommonPrefix(self, strs):
    prefix = '';
    # * is the unpacking operator, essential here
    for z in zip(*strs):
        bag = set(z);
        if len(bag) == 1:
            prefix += bag.pop();
        else:
            break;
    return prefix;


#Divide-and-Conquer Approach, python, 44ms 
 



class Solution:
    # @param {string[]} strs
    # @return {string}

    def longestCommonPrefix(self, strs):
        if not strs: return ""
        total = len(strs)
        l = min([len(x) for x in strs])
        g = 2
        while g / 2 < total:
            for i in xrange((total+g-1)/g):
                if i*g+g/2 < total:
                    while l and strs[i*g][:l] != strs[i*g+g/2][:l]: l-=1
            g *= 2
        return strs[0][:l]



相关文章
|
5月前
Leetcode 516. Longest Palindromic Subsequence
找到一个字符串的最长回文子序列,这里注意回文子串和回文序列的区别。子序列不要求连续,子串(substring)是要求连续的。leetcode 5. Longest Palindromic Substring就是求连续子串的。
22 0
|
5月前
|
Java
Leetcode 3. Longest Substring Without Repeating Characters
此题题意是找出一个不包含相同字母的最长子串,题目给出了两个例子来说明题意,但这两个例子具有误导性,让你误以为字符串中只有小写字母。还好我是心机boy,我把大写字母的情况也给考虑进去了,不过。。。。字符串里竟然有特殊字符,于是贡献了一次wrong answer,这次我把ascii字符表都考虑进去,然后就没问题了。这个故事告诫我们在编程处理问题的时候一定要注意输入数据的范围,面试中可以和面试官去确认数据范围,也能显得你比较严谨。
27 3
LeetCode 424. Longest Repeating Character Replacem
给你一个仅由大写英文字母组成的字符串,你可以将任意位置上的字符替换成另外的字符,总共可最多替换 k 次。在执行上述操作后,找到包含重复字母的最长子串的长度。
75 0
LeetCode 424. Longest Repeating Character Replacem
LeetCode 409. Longest Palindrome
给定一个包含大写字母和小写字母的字符串,找到通过这些字母构造成的最长的回文串。 在构造过程中,请注意区分大小写。比如 "Aa" 不能当做一个回文字符串。
53 0
LeetCode 409. Longest Palindrome
LeetCode 395. Longest Substring with At Least K
找到给定字符串(由小写字符组成)中的最长子串 T , 要求 T 中的每一字符出现次数都不少于 k 。输出 T 的长度。
57 0
LeetCode 395. Longest Substring with At Least K
|
Windows
LeetCode 388. Longest Absolute File Path
我们致力于寻找我们文件系统中文件的最长 (按字符的数量统计) 绝对路径。例如,在上述的第二个例子中,最长路径为 "dir/subdir2/subsubdir2/file2.ext",其长度为 32 (不包含双引号)。
51 0
LeetCode 388. Longest Absolute File Path
|
存储
LeetCode 329. Longest Increasing Path in a Matrix
给定一个整数矩阵,找出最长递增路径的长度。 对于每个单元格,你可以往上,下,左,右四个方向移动。 你不能在对角线方向上移动或移动到边界外(即不允许环绕)。
45 0
LeetCode 329. Longest Increasing Path in a Matrix
|
算法
LeetCode 300. Longest Increasing Subsequence
给定一个无序的整数数组,找到其中最长上升子序列的长度。
34 0
LeetCode 300. Longest Increasing Subsequence
|
算法
LeetCode 128. Longest Consecutive Sequence
给定一个未排序的整数数组,找出最长连续序列的长度。 要求算法的时间复杂度为 O(n)。
63 0
LeetCode 128. Longest Consecutive Sequence
|
Java 程序员 开发者
LeetCode第三题(Longest Substring Without Repeating Characters)三部曲之三:两次优化
本文是《LeetCode第三题(Longest Substring Without Repeating Characters)三部曲》的第二篇,前一篇文章已经列出了完整的解题思路,今天来将此思路转化为具体的Java代码
LeetCode第三题(Longest Substring Without Repeating Characters)三部曲之三:两次优化