java 14.最长公共前缀(#1排序).java

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 14.最长公共前缀(#1排序).java相关的知识,希望对你有一定的参考价值。

"""
Write a function to find the longest common prefix string amongst an array of strings.
"""
class Solution(object):
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        
        res = '';
        j = 0;
        
        if not strs:
            return '';
            
        length = len(min(strs)); ## waste some time 
        
        while(j < length):
            temp = res;
            res += strs[0][j]; 
            for i in range(1,len(strs)):
                if strs[i][j] != res[-1]:
                    return temp;
            j += 1;
            
        return res;


"""
"""
class Solution(object):
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        
        res = '';
        j = 0;
        
        if not strs:
            return '';
        
        
        while(1):
            temp = res;
            for i in range(0,len(strs)):
                if j >= len(strs[i]) or (i > 0 and strs[i][j] != strs[i-1][j]):
                    return res;
            res += strs[0][j];
            j += 1;
            
        return res;
class Solution {
    public String longestCommonPrefix(String[] strs) {
        if (strs == null || strs.length < 1) return "";
        int len = strs.length;
        if (len == 1) return strs[0];
        int j = 0;
        while (true) {
            for (int i = 0; i < len; i++) {
                if (j >= strs[i].length() || (i > 0 && strs[i].charAt(j) != strs[i - 1].charAt(j))) {
                    return strs[i].substring(0, j);
                }
            }
            j++;
        }
    }
}

/*

[]
["abc"]
["a","ab","ac","ad"]
["ab","abc","abc","abdc"]
["ab"]
["a","b"]
["aa","a"]

*/
class Solution {
    public String longestCommonPrefix(String[] strs) {
        if (strs == null || strs.length < 1) return "";
        StringBuilder res = new StringBuilder();
        Arrays.sort(strs);
        char[] a = strs[0].toCharArray();
        char[] b = strs[strs.length - 1].toCharArray();
        for (int i = 0; i < a.length && i < b.length; i++) {
            if (a[i] == b[i]) {
                res.append(a[i]);
            } else {
                return res.toString();
            }
        }
        return res.toString();
    }
}

以上是关于java 14.最长公共前缀(#1排序).java的主要内容,如果未能解决你的问题,请参考以下文章

java 14.最长公共前缀(#1排序).java

java 14.最长公共前缀(#1排序).java

java 14.最长公共前缀(#1排序).java

java 14.最长公共前缀(#1排序).java

14. 最长公共前缀 Java

LeetCode-14. 最长公共前缀(java)