其他分享
首页 > 其他分享> > leetcode14:最长公共前缀 还有其他解法

leetcode14:最长公共前缀 还有其他解法

作者:互联网

 

 

================Python=============

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        if len(strs) == 0:
            return ""
        return reduce(self.helper, strs)

    def helper(self, str1, str2):
        ans = ""
        if len(str1) == 0 or len(str2) == 0:
            return ans
        n = min(len(str1), len(str2))
        for i in range(n):
            if str1[i] == str2[i]:
                ans += str1[i]
            else:
                break
        return ans

=====================Go====================

func longestCommonPrefix(strs []string) string {
    if len(strs) == 0{
        return ""
    }
    var ans string
    ans = strs[0]
    n := len(strs)
    for i := 1; i < n; i++ {
        ans = longestCommonPrefixHelper(ans, strs[i])
        if ans == "" {
            return ans
        }
    } 
    return ans
    
}

func longestCommonPrefixHelper(str1, str2 string) string {
    if len(str1) == 0 || len(str2) == 0 {
        return ""
    }
    length := min(len(str1), len(str2))
    var ans string
    for i := 0; i < length; i++ {
        if str1[i] == str2[i] {
            ans += string(str1[i])
        } else{
            break
        }
    }
    return ans
}

func min(s1, s2 int) int {
    if s1 > s2 {
        return s2
    } else {
        return s1
    }
}

=======================Java===================

class Solution {
    
    public String longestCommonPrefix(String[] strs) {
        int len = strs.length;
        if (len == 0) {
            return "";
        }
        String res = strs[0];
        for (int i=1; i < len; i++) {
            res = longestCommonPrefixHelper(res, strs[i]);
        }
        return res;
    }

    public String longestCommonPrefixHelper(String str1, String str2) {
        
        int length = Math.min(str1.length(), str2.length());
        int index = 0;
        while (index < length && str1.charAt(index) == str2.charAt(index)) {
            index++;
        }
        return str1.substring(0, index);

    }
}

 

标签:return,前缀,strs,str2,str1,len,leetcode14,ans,解法
来源: https://www.cnblogs.com/liushoudong/p/13492643.html