leetcode刷题14 最长公共前缀 Longest Common Prefix(简单) Python

LeetCode 14. 最长公共前缀 Longest Common Prefix Table of Contents 一、中文版 二、英文版 三、My answer 四、解题报告 一、中文版 编写一个函数来查找字符串数组中的最长公共前缀。 如果不存在公共前缀,返回空字符串""。 示例1: 输入: ["flower","flow","flight"] 输出: "fl" 示例2: 输入: ["dog","racecar","car"] 输出: "" 解释: 输入不存在公共前缀。 说明: 所有输入只包含小写字母a-z。 来源:力扣(LeetCode) 链... 阅读详情

编写一个函数来查找字符串数组中的最长公共前缀。

如果不存在公共前缀,返回空字符串 ""。

示例 1:

输入: ["flower","flow","flight"]

输出: "fl"

示例 2:

输入: ["dog","racecar","car"]

输出: ""

解释: 输入不存在公共前缀。

 

说明:

所有输入只包含小写字母 a-z 。

class Solution:
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        if len(strs) == 0: # 判断是否为空
            return ''
 
        if len(strs) == 1:
            return strs[0]
 
        # 只需要比较最大和最小的
        a = min(strs) # 当前列表的字符串中,每个字符串从第一个字母往后比较直至出现ASCII码 最小的字符串
        b = max(strs) # 当前列表的字符串中,每个字符串从第一个字母往后比较直至出现ASCII码 最大的字符串
 
        for i in range(len(a)):
            if a[i] != b[i]:
                return a[:i]  # 返回从第一个到首次不相等的前一个为止的新字符串a
        return a 


if __name__ == '__main__':
    s = Solution()
    print(s.longestCommonPrefix(["flower", "flow", "flight"]))

值得注意的是:Python里面的min(),max()函数并不是计算字符串长度的,二十把每个字符串的ascii码相加,分别找出最大、最小值的函数

东方财富网 数据访问接口及字段说明 东方财富网 数据访问接口和字段说明 阅读详情

相关推荐

超详细流式细胞术全流程解析:从样本制备到结果分析全攻略

流式细胞术(Flow Cytometry)是现代生物学和医学研究中不可或缺的高通量分析技术,可实现对细胞表型、功能状态、细胞周期等多维度参数的快速检测。本文将从实验全流程出发,详解样本制备、上机操作、参数设置及结果处理的核心要点,帮助科研人员精准掌握流式实验关键技术。

good_rrrrr的博客 3867

leetcode5 最长公共前缀三种python解法

因此只要选择list中任意一个字符串作为子字符串,循环检索list每个字符串(比较要注意,比较如果没有就让子字符串从后面-1,此时不去检索下一个,而是一直循环在这个字符串上,接着find直至找到相同的部分,因为是公共的必须满足每一个都找到相同的)*strs使用解包操作符,把strs元素拆分册灰姑娘多个单独的参数,zip把相同位置的字符打包成元组,for中如果有字符不相同就返回strs中任意一个字符串的前i-1个元素;如果没有就返回长度最小的一定是公共的。如果不存在公共前缀,返回空字符串。

weixin_64612422的博客 673

VS2022 LNK1168无法打开进行写入 解决办法

C语言编程---VS---错误和警告---链接器工具错误---LNK1168--无法打开进行写入

weixin_67166415的博客 7154

Longest Common Prefix

#14 Longest Common Prefix 最大公共前缀。注意不是字符串,是前缀,因此会方便很多。 如输入["flower","flow","flight"],返回字符串"fl";若没有,则返回空字符串。 1、对所有字符串二分查找公共字符串+递归。 去找前面一半的公共字符串和后面一般的公共字符串,再去找他们的公共字符串。以此不断二分下去,递归查找。 最后肯定归结到判断2个字符串的...

ai136172022的博客 421

高性能网站设计之缓存更新的套路

看到好些人在写更新缓存数据代码时,先删除缓存,然后再更新数据库,而后续的操作会把数据再装载的缓存中。然而,这个是逻辑是错误的。试想,两个并发操作,一个是更新操作,另一个是查询操作,更新操作删除缓存后,查询操作没有命中缓存,先把老数据读出来后放到缓存中,然后更新操作更新了数据库。于是,在缓存中的数据还是老的数据,导致缓存中的数据是脏的,而且还一直这样脏下去了。 我不知道为什么这么多人用的都是这

代码技巧 1万+

基于单片机控制的开关电源设计

采用开关电源技术和MCU模块,凭借可靠性高、易于调适的特点,可以更高效地发挥出二者的优势,从而实现更好的组合。stm32的起动模式是通过Boot0和Boot1两个管脚的高低电平来决定的,当stm32被供电之后,这两个管脚的电平。在 VCC上,键盘的一头(列线)被连接到 VCC上,而在“0”的编程输出中,则用来进。,在开关管打开的情况下,由输入电力供给电流,感应装置存储   Buck变换器是一种非隔离式的电压转换器[10]整流电路对输入电压进行整流,再经过滤波电路,即Dc电压是直流/直流变换器的直流输入。

QQ1694456187的博客 2307

算法:最长公共前缀(longest-common-prefix)。

编写一个函数来查找字符串数组中的最长公共前缀。 如果不存在公共前缀,返回空字符串""。

孤芳不自赏 6864

深度学习之常用算子介绍

打开 onnx 模型图,可以看到它是一个有向无环图。除了 Input、Output ,其他都是算子(是操作,而不是节点)在ONNX(Open Neural Network Exchange)模型中,除了输入和输出,其他都是算子(Operations)。算子是表示神经网络模型中的不同操作或层的元素。一个ONNX模型由一系列算子组成,通过连接这些算子来定义模型的计算流程。

ueke1的博客 8459

最长公共前缀 python_【LeetCode】14.最长公共前缀(python版)

题目描述:编写一个函数来查找字符串数组中的最长公共前缀。如果不存在公共前缀,返回空字符串 “”。示例 1:输入: ["flower","flow","flight"]输出: "fl"示例 2:输入: ["dog","racecar","car"]输出: ""解释: 输入不存在公共前缀。说明:所有输入只包含小写字母 a-z 。思路:本题虽然只是“容易”等级的题目,但是可以有至少五种解法,而且这是一个...

weixin_39632293的博客 1109

狗都能看懂的MAML原理讲解和代码实现

meta-leaning指的是元学习,元学习是深度学习的一个分支,一个好的元模型(meta-learner)应该具备对新的、少量的数据做出快速而准确的学习。通俗的来讲, 对于人来说,给几张橘猫的图片让看一下,再给你几张没见过的英短猫图片,你一定能很快识别出来都是猫。但是对于神经网络来说,并非如此。如果让一个小汽车分类网络去识别不同的大货车,那效果肯定很差。而传统的CNN网络都是输入大量的数据,然后进行分类的学习。但是这样做的问题就是,神经网络的通用性太差了,根本达不到“智能”的标准。而人类的认知系统,可以通

个人学习笔记 6万+

汇川AM系列ethercat控制伺服的使用说明(含转矩模式)

本文以一个实际例子,介绍ethercat伺服驱动器的工作原理,以及在汇川AM系列PLC中,如何点动、定位、速度、转矩控制ethercat伺服。

qq_34047402的博客 5110

LeetCode(#14) 最长公共前缀(python)

如果不存在公共前缀,返回空字符串 “”。 示例 1: 输入: [“flower”,“flow”,“flight”] 输出: “fl” 示例 2: 输入: [“dog”,“racecar”,“car”] 输出: “” 解释: 输入不存在公共前缀。 说明: 所有输入只包含小写字母 a-z 方法一: 灵活运用zip(*)和set() strs=["123","flow","flight"] zipped...

sinat_32512123的博客 351

在 ABAP 中把变量一次写对:深入理解 FINAL 内联声明与不可变变量

摘要:ABAP中的FINAL声明操作符用于定义不可变变量,强调"当前上下文中的唯一写位置",能有效防止变量被意外修改,提升代码健壮性和可读性。官方建议优先在单次赋值的场景使用FINAL替代DATA。其核心规则包括:1)写位置唯一但可多次执行(如循环内);2)不创建块级作用域;3)对引用变量仅约束引用本身而非对象内容。典型适用场景包括:结果值只读、输入快照保存和中间结果保护。例外情况如游标变量不适用,因需多次写操作。正确使用FINAL可显著降低代码维护风险。

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 1044

Leetcode14. Longest Common Prefix 最长公共前缀

14. Longest Common Prefix 最长公共前缀 标签: Leetcode 题目地址:https://leetcode-cn.com/problems/longest-common-prefix/ 题目描述 编写一个函数来查找字符串数组中的最长公共前缀。 如果不存在公共前缀,返回空字符串 ""。 示例 1: 输入: ["flower",&quo

CoderWangSon 274

蓝牙模块HM-10手册

蓝牙模块HM-10手册,该手册对蓝牙模块HM-10进行了详细的介绍和使用方法以及一些AT指令。

ET2012新版免狗免安装绿色软件

ET2012新版免狗免安祖昂绿色软件。,新界面,新视觉,

【LeetCode】14. Longest Common Prefix

Problem Algorithmic thinking 方法一:水平扫描法 Java解法: public String longestCommonPrefix(String[] strs) { if (strs.length == 0) return ""; String prefix = strs[0]; for (int i = 1; i < strs....

E.W的博客 1232

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

14. Longest Common Prefix [easy] (Python)

题目链接https://leetcode.com/problems/longest-common-prefix/题目原文 Write a function to find the longest common prefix string amongst an array of strings. 题目翻译写个函数,找出一个字符串数组中所有字符串的最长公共前缀。 题目描述不清晰。。。补充几个例子,

Coder_Orz的博客 1万+

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

Leetcode刷题笔记之 Longest Common Prefix(python实现)

Leetcode刷题笔记之 Longest Common Prefix(python实现)问题描述程序实现总结 问题描述 Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty strin...

weixin_44239314的博客 422

LeetCode 14 — Longest Common Prefix(C++ Java Python)

题目:http://oj.leetcode.com/problems/longest-common-prefix/ Write a function to find the longest common prefix string amongst an array of strings. 题目翻译: 编写一个函数找出字符串数组的最长公共前缀子串。 分析:         如果字符串数

龙之梦 3773

(三刷) leetcode 14. Longest Common Prefix(python)

总的来说这道题是一道经典题目,值得一刷在刷,其实就是在求最长公共前缀字符串,其解法也是多种多样,有的比较容易理解,实现也比较方便,有的不容易理解,实现也比较麻烦,是一道仁者见仁智者见智的题目,高手的解法自然是会比较花样百出,新手看了也有自己的简单解法,无非就是效率的问题。原题链接:https://leetcode.com/problems/longest-common-prefix/您的支持是我最大的动力。

王大呀呀的博客 1085

**Leetcode 14 Longest Common Prefix

Leetcode 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:...

qq_43271202的博客 223

leetcode python3 简单题14. Longest Common Prefix

1.编辑器 我使用的是win10+vscode+leetcode+python3 环境配置参见我的博客: 链接 2.第一题 (1)题目 英文: Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an e...

从此做一个俗人 318

14 - Longest Common Prefix - python

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","...

Forlogenの解忧杂货铺 558

LeetCode 14. 最长公共前缀(Longest Common Prefix)

这篇文章详细讲解了 LeetCode 第 14 题"最长公共前缀"的解法。摘要如下: 题目要求在字符串数组中寻找所有字符串的最长公共前缀。文章分析纵向扫描法是最优解,即以第一个字符串为基准,逐字符与其他字符串同位置比较,遇到不匹配或越界时返回当前前缀。提供了 Python 和 Java 的实现代码,并比较了两种语言的差异。文章还讨论了时间复杂度(O(S))、空间复杂度(O(1)),指出常见错误如空字符串处理和索引越界问题,最后简要提及其他解法思路(水平扫描、分治法)。该问题考察字符串处理和边界条件处理能力,

2603_95532426的博客 359

leetcode第14题——*Longest Common Prefix

题目 Write a function to find the longest common prefix string amongst an array of strings. 思路 寻找字符串数组中所有字符串的最长公共前缀,注意是所有字符串的公共前缀,比如数组['hello', 'hell', 'he']的最长公共前缀为'he'。显然如果存在空字符串则公共前缀为空字符串。可以先将第一个字

buptlrw的专栏 870

【力扣Leetcode题解系列之0014—Longest Common Prefix 最长公共前缀】

本文介绍了求解字符串数组最长公共前缀的多种解法及其多语言实现。主要方法包括:1)遍历前缀子串法,逐个检查公共前缀;2)利用集合特性判断公共前缀;3) 基于最短字符串遍历比较;4)排序后比较首尾字符串。文章提供了Python、Java和C语言的实现代码,展示了不同语言下的解决方案。这些方法各有优缺点,适用于不同场景,其中遍历最短字符串和排序法相对高效。

youngerwang的博客 438

14. Longest Common Prefix

题目: LeetCode:14. Longest Common Prefix 描述: Write a function to find the longest common prefix string amongst an array of strings. 求字符串数组的最长公共前缀。 分析: 思路: 1、遍历vector中每个字串,将之与之前得到的公共字串进行比较; 2、将首个...

dbb191379的博客 143
上一篇: leetcode刷题9 回文数 Palindrome Number(简单) Python Java
下一篇: leetcode刷题21 合并两个有序链表 Merge Two Sorted Lists(简单) Python Java
SpringRolls
博客等级 码龄9年 73粉丝 129原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值