码迷,mamicode.com
首页 > 其他好文 > 详细

#14 Longest Common Prefix

时间:2019-11-13 00:54:18      阅读:88      评论:0      收藏:0      [点我收藏+]

标签:func   return   note   cti   ges   Plan   ace   stc   lis   

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

If there is no common prefix, return an empty string "".

Example 1:

Input: ["flower","flow","flight"]
Output: "fl"

Example 2:

Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.

Note:

All given inputs are in lowercase letters a-z.


 

Solution1:

class Solution:
  def longestCommonPrefix(self, strs: List[str]) -> str:
    output = ""
    next = True
    index = 0
    # check if empty list
    if len(strs) == 0:
      return ""
    # check if empty string inside list
    for i in range(len(strs)):
      if len(strs[i]) == 0:
      return ""
    # compare each letter of each string
    while(next):
      letter = strs[0][index]
      for i in range(len(strs)):
        if strs[i][index] != letter:
          next = False
          break
      if next:
        output += letter
        index += 1
      for i in range(len(strs)):
        if len(strs[i]) <= index:
        next = False

    return output

 

 

Solution2:

class Solution:
  def longestCommonPrefix(self, strs: List[str]) -> str:
    if len(strs) == 0:
      return ""
    output = ""
    index = 0
    while True:
      letter = ‘‘
      for word in strs:
        if len(word) == index:
          return output
        else:
          if letter == ‘‘:
            letter = word[index]
          else:
            if word[index] != letter:
              return output
      index += 1
      output += letter

 

#14 Longest Common Prefix

标签:func   return   note   cti   ges   Plan   ace   stc   lis   

原文地址:https://www.cnblogs.com/mrdoghead/p/11846257.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!