zoukankan      html  css  js  c++  java
  • Longest Common Prefix

    Write a function to find the longest common prefix string amongst an array of strings.

    分析:

    对一组字符串找到最长公共前缀。

    因为只是找前缀所以可以以第一个字符串为基础,按个字符与其它字符串比较,直到有字符串已经遍历完或者碰到不一致的字符,返回到当前为止第一个字符串的前缀即可。

    class Solution:
    
        # @return a string
        def longestCommonPrefix(self, strs):
            if not strs or not strs[0]:
                return ""
    
            first = strs[0]
            for i in range(len(first)):
                for s in strs[1:]:
                    if i >= len(s) or s[i] != first[i]:
                        return first[:i]
            return first
    
    if __name__ == '__main__':
        s = Solution()
        assert s.longestCommonPrefix([]) == ""
        assert s.longestCommonPrefix([""]) == ""
        assert s.longestCommonPrefix(["a", "b"]) == ""
        assert s.longestCommonPrefix(["aa", "aa"]) == "aa"
        print 'PASS'

    小结:

    这个问题比较简单,也没有太多程序编写上的陷阱,按直觉解法写出代码就可以Accepted。

  • 相关阅读:
    王道训练营-C语言-1
    错排问题
    王道训练营-C语言-1
    图文处理 生成海报
    根据经纬度按距离排序
    vue总结
    docker+consul
    doker es
    知识库
    php笔记
  • 原文地址:https://www.cnblogs.com/openqt/p/4033672.html
Copyright © 2011-2022 走看看