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。

原文地址:https://www.cnblogs.com/openqt/p/4033672.html