• 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);
    
        }
    }
  • 相关阅读:
    nexus6 bootloader上锁报错 FAILED (remote: 'unknown command')
    在线kali
    优秀硬件品牌清单
    路由器AC1200到底什么意思?
    第三方路由器固件合集
    无线芯片集合
    编程语言中三大语句结顺序、判断、循环结构本质是什么?
    刷入twrp卡fastboot
    一加7安卓10如何切换ab分区
    一家安卓手机上的猎豹清理大师、mt管理器闪退
  • 原文地址:https://www.cnblogs.com/liushoudong/p/13492643.html
Copyright © 2020-2023  润新知