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。

  • 相关阅读:
    20209/29
    2020/9/30
    2020/10/1
    ATM测试总结报告
    20201020 千锤百炼软工人
    20201024 千锤百炼软工人
    20201025 千锤百炼软工人
    20201023 千锤百炼软工人
    20201018 千锤百炼软工人
    20201022 千锤百炼软工人
  • 原文地址:https://www.cnblogs.com/openqt/p/4033672.html
Copyright © 2011-2022 走看看