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);
    
        }
    }
  • 相关阅读:
    JVM调优(一)——参数查询和问题排查
    spring-cloud feign (web服务客户端)(四)
    spring-cloud hystrix(三)
    springCloud ribbon均衡负载的配置及原理 (二)
    maven
    springCloud Eureka 注册中心原理及配置理解(一)
    threadLocal 的使用及意义
    数据库引擎类型
    sql 优化
    sql 的执行计划理解
  • 原文地址:https://www.cnblogs.com/liushoudong/p/13492643.html
Copyright © 2011-2022 走看看