zoukankan      html  css  js  c++  java
  • leetcode14:最长公共前缀

    编写一个函数来查找字符串数组中的最长公共前缀。

    如果不存在公共前缀,返回空字符串 ""

    输入: ["flower","flow","flight"]
    输出: "fl"

    方法一:横向扫描

    //Python3
    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
    //Java
    class
    Solution { public String longestCommonPrefix(string[] strs) { if (strs == null || strs.length == 0) { return ""; } String perfix = strs[0]; int count = strs.length; for (int i = 1; i < count; i++) { prefix = longestCommonPrefix(prefix, strs[i]); if (prefix.length() == 0) { break; } } return prefix; } public String longestCommonPrefix(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); } }
    //Golang
    func longestCommonPrefix(strs []string) string { if len(strs) == 0 { return "" } prefix := strs[0] count := len(strs) for i := 1; I < count; i++ { prefix = lcp(prefix, strs[I]) if len(prefix) == 0 { break } } return prefix } func lcp(str1, str2 string) string { length := min(len(str1), len(str2)) index := 0 for index < length && str1[index] == str2[index] { index++ } return str1[:index] } func min(x, y int) int { if x < y { return x } return y }
  • 相关阅读:
    list for循环中删除元素
    XMLFeedSpider例子
    myeclipse一直卡在loading workbench解决方法
    代码
    在Github上面搭建Hexo博客(一):部署到Github
    RegEX正则表达式截取字符串
    将后台值传单前台js接收
    C# List<T>泛型用法
    基于jQuery——TreeGrid
    在线编程学习网站
  • 原文地址:https://www.cnblogs.com/liushoudong/p/13152033.html
Copyright © 2011-2022 走看看