zoukankan      html  css  js  c++  java
  • [LeetCode] 14. Longest Common Prefix 最长共同前缀

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

    If there is no common prefix, return an empty string "".

    Example 1:

    Input: ["flower","flow","flight"]
    Output: "fl"
    

    Example 2:

    Input: ["dog","racecar","car"]
    Output: ""
    Explanation: There is no common prefix among the input strings.

    这题有好几种解法,个人认为会1,2的解法就可以了,但这种多方法解题的思路可以好好学习一下。具体可参考:Longest Common Prefix

    1. 一个一个字符串取比较word by word matching:

    先拿前2个,从第一位开始比较,直到发现有不同的字符,此时前面一样的字符串在去和后面的字符串比较,直到结束。可以用递归。

    Time: O(n*m) (n是字符串个数,m是字符串最长长度)  Space: O(m)

    2. 一个字符一个字符的比较character by character matching:

    所有的字符串同时比较第1个,第2个.......,发现有不同的出现,之前一样的就是找到的最长共同前缀。Time: O(n*m) (n是字符串个数,m是字符串最长长度) Space: O(m)

    3. divide and conquer: 

    把所有字符串分成两组,分别去比较,最后都剩一个的时候,两组在比较。Time: O(n*m), Space: O(n*logm)

    4. 二分法Binary Search:

    先找到最短的字符串,然后把这个最短的字符串二分成前面和后面两部分,前面的和所有剩下字符串比较,如果一样在比较后面的,如果有不一样的,则后面的部分不用比较了,前面的部分在二分比较。Time: O(n*m*logm), Space: O(m)

    5. 使用Trie:

    首先了解Trie数据结构,然后把所有的字符串都执行一遍插入到Trie,然后读取Trie中最后一个没有分支的node,此时之前这些字符就是答案。

    Time: O(n*m + m), Space: O(26*m*n) ~ O(m*n)

    Java: Method 1

    public class Solution {
        public String longestCommonPrefix(String[] strs) {
            if (strs == null || strs.length == 0) {
                return "";
            }
            String prefix = strs[0];
            for(int i = 1; i < strs.length; i++) {
                int j = 0;
                while( j < strs[i].length() && j < prefix.length() && strs[i].charAt(j) == prefix.charAt(j)) {
                    j++;
                }
                if( j == 0) {
                    return "";
            }
                prefix = prefix.substring(0, j);
            }
            return prefix;
        }
    
    }  

    Java: Method 2

    public class Solution {
        public String longestCommonPrefix(String[] strs) {
            if (strs == null || strs.length == 0) return "";
            String res = new String();
            for (int j = 0; j < strs[0].length(); ++j) {
                char c = strs[0].charAt(j);
                for (int i = 1; i < strs.length; ++i) {
                    if (j >= strs[i].length() || strs[i].charAt(j) != c) {
                        return res;
                    }
                }
                res += Character.toString(c);
            }
            return res;
        }
    }
    

    Java: Method 2

    public class Solution {
        public String longestCommonPrefix(String[] strs) {
            if (strs == null || strs.length == 0) return "";
            for (int j = 0; j < strs[0].length(); ++j) {
                for (int i = 0; i < strs.length - 1; ++i) {
                    if (j >= strs[i].length() || j >= strs[i + 1].length() || strs[i].charAt(j) != strs[i + 1].charAt(j)) {
                        return strs[i].substring(0, j);   
                    }
                }
            }
            return strs[0];
        }
    }
    

    Python: Method 2

    class Solution(object):
        def longestCommonPrefix(self, strs):
            """
            :type strs: List[str]
            :rtype: str
            """
            if not strs:
                return ""
    
            for i in xrange(len(strs[0])):
                for string in strs[1:]:
                    if i >= len(string) or string[i] != strs[0][i]:
                        return strs[0][:i]
            return strs[0]
    

    C++: Method 2

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

      

    All LeetCode Questions List 题目汇总

      

      

  • 相关阅读:
    结对编程2
    结对编程总结:简单的四则运算生成程序
    我的结对项目心得与代码规范
    一个团队和他们的调查表-----("调查表与调查结果分析"心得体会)
    目标?我定好了!(我的软件工程课目标)
    Jmeter响应数据为乱码的处理
    软件工程课程建议
    结对编程之Fault、Error、Failure
    我的结对项目编程感想
    调查问卷后的心得
  • 原文地址:https://www.cnblogs.com/lightwindy/p/8495679.html
Copyright © 2011-2022 走看看