#14 Longest Common Prefix

陌路散爱 提交于 2019-12-04 07:17:15

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

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!