Leecode 14 longest common prefix

topic

Here Insert Picture Description

answer

  • To obtain the length of the shortest string
  • The minimum length of the character in the first string, determines whether all subsequent recursive string prefix also contain, if contained, are added to the Result result, there is a character string containing no iteration directly returns the result
    code is implemented as follows:
class Solution(object):
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        result = ''
        if strs == [] or '' in strs:
            return ''
        else:
            N = len(strs[0])
            #更新最短字符串的长度
            for s in strs:
                if len(s) < N:
                    N = len(s)
            #迭代过程
            for j in range(N):
                tmp = strs[0][j]
                for i in range(len(strs)):
                    t = strs[i][j]
                    if tmp != t:
                        return result
                result += strs[0][j]
        return result

Here Insert Picture Description

Published 52 original articles · won praise 5 · Views 3969

Guess you like

Origin blog.csdn.net/Pang_ling/article/details/105376986