最长公共前缀

LeetCode||最长公共前缀——编写一个函数来查找字符串数组中的最长公共前缀。 如果不存在公共前缀,返回空字符串 ""。 题目描述: 编写一个函数来查找字符串数组中的最长公共前缀。 如果不存在公共前缀,返回空字符串""。 算法解析: 输入的是一个字符串数组,需要分析的是字符串,既然是所有元素的公共前缀,那么必然是从元素开头开始,所以我们用遍历元素的方法: 前面我们已经讲过了indexOf()和substring()方法,所以我们运用这两个方法就能解决问题 程序 class Solution ... 阅读详情

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

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

示例 1:
输入: ["flower","flow","flight"]
输出: "fl"
示例 2:
输入: ["dog","racecar","car"]
输出: ""
解释: 输入不存在公共前缀。
说明:

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


解法1:

思路:纵向对比,就从位置0开始,对每一个位置比较所有的字符串,直到遇到不匹配的字符为止。(注意i==strs[j].length()||strs[j].charAt(i)!=strs[0].charAt(i) 位置不能反,必须先判断前面这句)

class Solution {
    public String longestCommonPrefix(String[] strs) {
        if(strs.length==0){
            return "";
        }
        for(int i=0;i<strs[0].length();++i){
            for(int j=1;j<strs.length;++j){
                if(i==strs[j].length()||strs[j].charAt(i)!=strs[0].charAt(i)){
                    return strs[0].substring(0,i);
                }
            }
        }
        return strs[0];
    }
}

解法2:

思路:*leetcode高分解法:其实思路就是跟上面的算法有一点不同,上面的公共前缀初始为零然后逐渐增加,下面就是初始为第一个字符串的长度然后逐渐递减。但是下面算法执行5ms,上面12ms*。

class Solution {
    public String longestCommonPrefix(String[] strs) {
        if(strs.length == 0){
            return "";
        }
        String prefix = strs[0];
        for (int i = 1; i < strs.length; i++) {
            while (strs[i].indexOf(prefix) != 0) {
                prefix = prefix.substring(0, prefix.length() - 1);
                if (prefix.length() == 0) {
                    return "";
                }
            }
        }
        return prefix;
    }
}


BB一句:

注意:String.indexOf() 、 substring()


欢迎关注我:一道小算法

LeetCode014——最长公共前缀 我的LeetCode代码仓:https://github.com/617076674/LeetCode 原题链接:https://leetcode-cn.com/problems/longest-common-prefix/description/ 题目描述: 知识点:字符串 思路一:以第一个字符串为基准找最长公共前缀 对于第一个字符串中的每一个字符,都要在后序的字符串中的相应位置找... 阅读详情

相关推荐

Aix升级和安装ssh配置过程

Aix升级和安装ssh配置过程Aix升级和安装ssh配置过程配置前背景配置步骤 Aix升级和安装ssh配置过程 部门IBM小型机的Aix操作系统需要进行ssh补丁修复,修复其实就是ssh版本你的升级,对升级的过程和中途遇到的问题做了记录如下。 配置前背景 操作系统: gdboss2/>uname -u //操作系统的Aix5.3 IBM,020693E5P gdboss2/&gt...

阿阿阿唱的博客 2998

LeetCode-14 最长公共前缀

编写一个函数来查找字符串数组中的最长公共前缀。 如果不存在公共前缀,返回空字符串""。 示例1: 输入: ["flower","flow","flight"] 输出: "fl" 示例2: 输入: ["dog","racecar","car"] 输出: "" 解释: 输入不存在公共前缀。 说明: 所有输入只包含小写字母a-z。 class Solution: def...

今晚打老虎 208

差分运放实战:如何快速计算带直流偏置的电路(附详细推导步骤)

本文详细解析了差分运放电路在带直流偏置设计中的核心计算方法和实战技巧。通过可视化参数关系和分步拆解,帮助工程师快速掌握电路设计精髓,包括虚短虚断原理、偏置电压计算及非理想因素处理,提升信号调理和传感器接口设计的效率与精度。

o4p5q6r7s的博客 424

(JS)最长公共前缀

编写一个函数来查找字符串数组中的最长公共前缀。 如果不存在公共前缀,返回空字符串 “”。 示例 1: 输入: ["flower","flow","flight"] 输出: "fl" 示例 2: 输入: ["dog","racecar","car"] 输出: "" 解释: 输入不存在公共前缀。 采用es6进行: let longestCommonPrefix = (strs) => { ...

whmJack的博客 2万+

SAP中错记虚拟利润中心的调整,冲销处理实例

我非CO专业顾问。工作中遇到的问题,也会找资料,分析,测试。有时这个过程会拿到结果,解决问题。遂将过程记录下来备查。读者请谨慎参考!EC-PCA: 利润中心记账流程_9ke0-CSDN博客。

专注SAP应用技术文章写作,致力于拉近用户与系统间的距离; 1806

Modelsim10.5_se安装(Win11)

modelsim是Mentor公司开发的优秀的HDL语言仿真软件。它能提供友好的仿真环境,采用单内核支持VHDL和Verilog混合仿真的仿真器。它采用直接优化的编译技术、Tcl/Tk技术和单一内核仿真技术,编译仿真速度快且编译的代码与平台无关。

m0_51186267的博客 9962

C++ 最长公共前缀

题目 最长公共前缀: 编写一个函数来查找字符串数组中的最长公共前缀。 如果不存在公共前缀,返回空字符串 “”。 示例 1: 输入: [“flower”,“flow”,“flight”] 输出: “fl” 示例 2: 输入: [“dog”,“racecar”,“car”] 输出: “” 解释: 输入不存在公共前缀。 该题目有两种解法: 1.纵向比较 因为提取的是前缀字符串,所以我们就选择strs数组中第一个元素作为基准。 然后我们将该元素与数组中每一个元素进行位比较。例如: (盗图,来自于这里) 比较所有元

YiYeZhiNian的博客 3547

游戏脚本开发避坑:Python调用OP模块实现阴阳师后台操作的5个关键点

本文深入探讨了使用Python调用OP模块开发《阴阳师》后台自动化脚本的5个核心避坑点。重点解析了窗口绑定、后台截图与图像识别、鼠标键盘模拟、脚本稳定性以及性能优化等关键环节的常见问题与实战解决方案,帮助开发者高效实现稳定的游戏后台挂机功能。

u0v1w2x3的博客 598

<LeetCode天梯>Day023 最长公共前缀(切片法) | 初级算法 | Python

????作者简介:大家好,我是车神哥,府学路18号的车神???? ????个人主页:应无所住而生其心的博客_府学路18号车神_CSDN博客 ????点赞➕评论➕收藏 == 养成习惯(一键三连)???? ????本系列主要以刷LeetCode(力扣)网站的各类题为标准,实现自我能力的提升为目标⚡ ⚡希望大家多多支持????~一起加油 ???? 专栏《LeetCode天梯》 工作日,周四了,今天比昨天还要热,午觉睡的出汗啊!最近在写小论文,晚上学雅思,但是刷题还是雷打不动的,坚持,坚持,坚持!!!只有坚持

车手只需要车和手,压力来自轮胎 1808

非sudo用户如何安全使用Docker:Rootless模式实战指南

Docker Rootless模式是一种基于Linux用户命名空间(userns)的容器运行时安全机制,它通过UID/GID映射、fuse-overlayfs文件系统和slirp4netns网络栈,在不提升权限的前提下实现容器隔离。其核心原理是将容器内root身份映射为宿主机非特权用户,从而规避docker组等价root的安全风险。相比传统root模式,Rootless在权限控制、逃逸防护和多租户隔离方面具备天然优势,适用于CI/CD流水线、Kubernetes边缘节点及受限生产环境。本文聚焦无sudo权限

weixin_30274627的博客 357

uniapp [全端兼容] - 实现接入集成高德地图搜索地址及选择位置功能,搜索框检索选择地点并返回经纬度及详细省市区县街道地址,用户搜索历史及清空历史记录,选择地址自动获取周边位置列表/地图移动选点

uni-app,高德地图,h5移动端网页,微信小程序,支付宝小程序,Android安卓,苹果ios,app,nvue,Uniapp高德地图,在地图上选择或搜索指定地点,打开地图选择位置,关联地址搜索,输入地址返回附近地址列表,uniApp高德地图地址搜索,搜索框历史记录,关键字搜索,周边查询,搜索位置,uniapp对接高德实现搜索出现地址以及保存搜索记录,集成高德地图,实现精准位置选点功能,获取当前定位城市,如何实现搜索功能,获取省份城市区街道详细地址经纬度,移动选点标记位置,在地图上进行选择位置选点、搜索

🏆 前端领域优质创作者 1万+

【面试经典】最长公共前缀

最长公共前缀

weixin_74146322的博客 1117

详解大模型微调数据集构建方法(持续更新)

本文详细介绍了大模型微调数据集构建方法,希望能对学习大模型的同学们有所帮助。 文章目录 1. 前言 2. 微调数据集构建方法 2.1 方法一 2.2 方法二 2.3 方法三 2.4 方法四 2.5 方法五

herosunly的博客 28万+

解决最长公共前缀问题

利用python中的内置语言解决最长公共前缀问题

weixin_63890355的博客 765

复分析 阿尔福斯(Ahlfors) 第三版答案 英文

答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案

深度学习工具包 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")

14. 最长公共前缀

特别的,如果循环中,prefix长度为0,说明strs[0:i]范围内的所有字符串最长公共前缀为空串,后续的遍历也就没有意义了,直接break退出循环。这道题目我的思路很简单,就是求字符串切片中最短的那个字符串的长度n,然后从1开始一直到n,截取前面几个字符判断是否一致,如若一致,即继续截取下一个,直到求出最长的公共前缀。这道题目如果要求时间复杂度不高的话,实现起来还是需要一点技巧的,我的第一思路太暴力了,时间复杂度太高,测试点复杂一点的话,肯定是过不去的!如果不存在公共前缀,返回空字符串 “”。

ReganYue's Blog 689

Devexpress16.2.6破解工具

Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具

Code6 最长公共前缀

题目 leetcode14. 最长公共前缀 编写一个函数来查找字符串数组中的最长公共前缀。 如果不存在公共前缀,返回空字符串 “”。 示例 1: 输入: [“flower”,“flow”,“flight”] 输出: “fl” 示例 2: 输入: [“dog”,“racecar”,“car”] 输出: “” 解释: 输入不存在公共前缀。 说明: 所有输入只包含小写字母 a-z 。 代码 // C++ #include <string> #include <vector> #inclu

程序员Link 432

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

字符串最长公共前缀问题

字符串最长公共前缀问题 leetcode练题笔记第二篇 :) 问题描述 编写一个函数来查找字符串数组中的最长公共前缀。 如果不存在公共前缀,返回空字符串 “”。 示例 1: 输入: [“flower”,“flow”,“flight”] 输出: “fl” 示例 2: 输入: [“dog”,“racecar”,“car”] 输出: “” 解释: 输入不存在公共前缀。 说明: 所有输入只包含小写字母 a-z 。 解题思路 横向扫描法 依次遍历字符串数组中的每个字符串,对于每个遍历到的字符串,更新最长公共前缀,当遍

Annie_XiaoLou的博客 416

Leetcode之最长公共前缀

问题描述 编写一个函数来查找字符串数组中的最长公共前缀。 如果不存在公共前缀,返回空字符串 ""。 示例 1: 输入: ["flower","flow","flight"] 输出: "fl" 示例 2: 输入: ["dog","racecar","car"] 输出: "" 解释: 输入不存在公共前缀。 说明: 所有输入只包含小写字母 a-z 。 解法 先取第一个字符串作为起始公共...

qq_44711190的博客 378
上一篇: 实现strStr()
下一篇: 删除链表中的节点
coder_flag
博客等级 码龄9年 2粉丝 53原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值
⌂ 换网址