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

leedCode练题——14. Longest Common Prefix

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

标签:ring   longest   NPU   lse   github   bsp   ase   hub   amp   

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

标签:ring   longest   NPU   lse   github   bsp   ase   hub   amp   

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

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