leedCode练题——14. Longest Common Prefix

Posted smart-cat

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leedCode练题——14. Longest Common Prefix相关的知识,希望对你有一定的参考价值。

1、题目

14. Longest Common Prefix
 

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.

 

2、我的解法

# -*- coding: utf-8 -*-
# @Time : 2020/1/29 12:28
# @Author : SmartCat0929
# @Email : 1027699719@qq.com
# @Link : https://github.com/SmartCat0929
# @Site :
# @File : 14. Longest Common Prefix.py

from typing import List


class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
d = len(strs)
minLength = 999999
for str in strs:
thisLength = len(str)
if thisLength < minLength:
minLength = thisLength
res = ""
if d > 0:
for i in range(minLength):
n = 0
r = strs[0][i]
for j in range(d):
if r == strs[j][i]:
n = n + 1
if n == d:
break
else:
return res
res = res + r
return res
else:
return res


# print(Solution().longestCommonPrefix(["flower", "flow", "flight"]))
print(Solution().longestCommonPrefix([""]))

以上是关于leedCode练题——14. Longest Common Prefix的主要内容,如果未能解决你的问题,请参考以下文章

leedCode练题——9. Palindrome Number

leedCode练题——21. Merge Two Sorted Lists(照搬大神做法)

leedcode Longest Palindromic Substring

LeedCode3Sum

409. Longest Palindrome

14. Longest Common Prefix