Leetcode:14- Longest Common Prefix

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

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

例如:['abc','ab','a'],输出a

思路:从任意一个字符串开始,扫描该字符串,依次检查其他字符串的同一位置是否是一样的字符,当遇到不一样时则返回当前得到的前缀。

class Solution(object):
    def longestComminPrefix(self,strs):
        if strs == []:
            return ''
        for i in range(len(strs[0])):  #以第一个字符串为参照
            for str in strs:
                if len(str) <= i or str[i] != strs[0][i]:  #当前字符串短于第一个字符串扫描的位置,或者当前字符串的字符位与第一个字符串对照的字符位不同
                    return strs[0][:i]
        return strs[0]

if __name__=='__main__':
    solution = Solution()
    strs = ['abc','a','ab']
    print(solution.longestComminPrefix(strs))

 

posted @ 2017-12-28 10:28  十二Zh  阅读(97)  评论(0)    收藏  举报