leetcode: 14. Longest Common Prefix

来源:互联网 发布:做库存的软件 编辑:程序博客网 时间:2024/06/05 08:29

Problem

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

AC

class Solution():    def longestCommonPrefix(self, x):        if not x:            return ""        prefix, i = x[0], 1        while len(prefix) > 0:            while i < len(x) and x[i][:len(prefix)] == prefix:                i += 1            if i == len(x):                return prefix            prefix = prefix[:-1]        return ""if __name__ == "__main__":    assert Solution().longestCommonPrefix(["China", "Chinese", "Chipotle"]) == 'Chi'    assert Solution().longestCommonPrefix(["China", "", "Chipotle"]) == ''
原创粉丝点击