首页 > 其他 > 详细

leedCode练题——14. Longest Common Prefix

时间:2020-01-29 17:38:57      阅读:72      评论:0      收藏:0      [点我收藏+]

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

原文:https://www.cnblogs.com/Smart-Cat/p/12240688.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!