zoukankan      html  css  js  c++  java
  • 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);
    
        }
    }
  • 相关阅读:
    js验证身份证号,超准确
    C#对象序列化与反序列化
    寒冰王座[HDU1248]
    A C[HDU1570]
    循环多少次?[HDU1799]
    Play on Words[HDU1116]
    Fengshui-[SZU_B40]
    Travel Problem[SZU_K28]
    Big Event in HDU[HDU1171]
    Count the Trees[HDU1131]
  • 原文地址:https://www.cnblogs.com/liushoudong/p/13492643.html
Copyright © 2011-2022 走看看