leetcode笔记--Longest Common Prefix

来源:互联网 发布:maxonor创意公元软件 编辑:程序博客网 时间:2024/06/18 03:32

题目:难度(Easy)

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

分析:找字符串数组中字符串们的最长公共前缀

class Solution(object):    def longestCommonPrefix(self, strs):        """        :type strs: List[str]        :rtype: str        """        if len(strs) == 0:            return ""        #为smallLength给上第一个字符串长度的初值        smallLength = len(strs[0])        for s in strs:            if len(s) < smallLength:                smallLength = len(s)        #此时smallLength为最小长度,i指示第i个字符,j指示strs里的第j个字符串        endFor = False        i = 0        while i < smallLength:            #ch为第1个字符串的第i个字符            ch = strs[0][i]            j = 1            while j < len(strs):                if strs[j][i] != ch:                    endFor = True                    break                j += 1            if endFor is True:                break            i += 1        return strs[0][:i]


0 0
原创粉丝点击