【算法】LeetCode算法题-Length Of Last Word

LeetCode Length of Last Word 1. 题目Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string.If the last word does not exist, return 0.Note: A word is defi 阅读详情

这是悦乐书的第155次更新,第157篇原创


01 看题和准备

今天介绍的是LeetCode算法题中Easy级别的第14题(顺位题号是58)。给定一个字符串,包含戴尔字母、小写字母和空格,返回最后一个单词的长度,如果最后一个单词不存在则返回0。另外,单词不包含空格。例如:

输入: “Hello World”
输出: 5
说明:最后一个单词为world,其长度为5

本次解题使用的开发工具是eclipse,jdk使用的版本是1.8,环境是win7 64位系统,使用Java语言编写和测试。


02 第一种解法

第一步考虑特殊情况,传入的字符串全部由空格组成,这时可以直接返回0。

第二步,获取最后一个单词结束字符的位置。

既然是获取最后一个单词,那么最后一个单词的情况分两种:以单词结尾;不已单词结尾,后面还带了空格。

先将字符串转为字符数组,从后往前依次获取每一个字符,如果遇到空格,继续向前循环,直到第一个字符;反之则表示遇到了一个单词,将其位置记录为end。

第三步,获取最后一个单词开始字符的位置。接着第二步的索引继续向前判断,不过判断的条件变成了不等于空格,直到条件不满足,则表示此单词已经查找完毕,将其位置记录为start。

第三步,用end减去start,即为最后一个单词的长度。

public int lengthOfLastWord(String s) {
    if("".equals(s.trim())) { return 0; }
    int n = s.length()-1;
    char[] ch = s.toCharArray();
    while (n >= 0 && ch[n] == ' ') {
        n--;
    }
    int end = n;
    while(n >= 0 && ch[n] != ' ') {
        n--;
    }
    int start = n;
    return end - start;
}

03 第二种解法

既然此字符串是由大小写字母和空格组成,那么是否可以使用空字符串将其分割为多个子字符串?如果原字符串不包含空格,那么分割后还是该字符串;如果包含字符串,那么最后一个被分割出来的子字符串就是我们想要的最后的一个单词。和第一种解法最开始一样,特殊情况也是要考虑进去的。

public int lengthOfLastWord2(String s) {
    if("".equals(s.trim())) { return 0; }
    if (s.length() ==0 || s.indexOf(" ") == -1) {
        return s.length();
    }
    String[] arr = s.split(" ");
    return arr[arr.length-1].length();
}

04 第三种解法

将原字符串首尾的空格去掉,然后找到最后一次出现空格的位置,两者相减再减1即为最后单词的长度。

public int lengthOfLastWord3(String s) {
    return s.trim().length()-s.trim().lastIndexOf(" ")-1;
}

05 小结

以上就是全部内容,如果大家有什么好的解法思路、建议或者其他问题,可以下方留言交流,点赞、留言、转发就是对我最大的回报和支持!

薄膜比拟、开口截面扭转承载力以及风电混塔水平缝张开状态下抗扭承载力推导 风电混塔水平缝张开状态下的抗扭承载力推导,从弹性力学说起 阅读详情

相关推荐

【ZZULIOJ】郑州轻工业大学oj题解整合

写在前面 关于ZZULIOJ题解 学习编程,想要巩固无非就是刷题或者做项目,然后因为我大一开始是刷郑轻的题目,就想着自己整合一下自己写的题目。既是复习也是笔记吧。 题解(内有题目描述) 1000 整数a+b 1001 植树问题 1002 简单多项式求值 1003 两个整数的四则运算 1004 三位数的数位分离 1005 整数幂 1006 求等差数列的和 1007 鸡兔同笼 1008 美元和人民币 1009 求平均分 1010 求圆的周长和面积 1011 圆柱体表面积 1012 求绝对值 1013 求两点间

蒟蒻乱写的博客 29万+

python写算法题:leetcode: 58. Length of Last Word

class Solution(object): def lengthOfLastWord(self, s): """ :type s: str :rtype: int """ ret=0 lastch = len(s)-1 for _ in xrange(len(s)): ...

244

Arduino-CRSF库详解:嵌入式端CRSF协议解析与ELRS接收机集成

CRSF(Crossfire Serial Protocol)是一种面向FPV无人机的轻量级、高实时性串行通信协议,采用单总线异步传输与8位CRC-8校验机制,广泛应用于遥控链路与遥测交互。其核心在于帧同步(0xC8起始字节)、反相逻辑电平及无重传的广播式设计,对嵌入式平台的UART精度、电平匹配和状态机健壮性提出严苛要求。Arduino-CRSF库正是为资源受限MCU(如ESP32、STM32、ATmega328P)提供零配置、中断安全的协议解析能力,封装了CRC查表计算、超时恢复、多级同步验证等关键机制

weixin_35756690的博客 430

LeetCode OJ算法题(五十七):Length of Last Word

题目: Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string. If the last word does not exist, return 0. Note: 

op_yu的专栏 380

LangGraph实战:用Python异步构建智能客服多轮对话系统(附完整代码)

本文详细介绍了如何使用LangGraph框架和Python异步编程构建一个高性能的智能客服多轮对话系统。通过将对话流程建模为有向图,结合thread_id实现多用户对话隔离,并利用异步节点提升系统并发处理能力,有效解决了传统客服系统上下文遗忘与高并发瓶颈问题。文章提供了从环境搭建、状态管理、异步优化到复杂业务逻辑与部署的完整实战代码。

weixin_29055137的博客 157

xsens IMU配置

1.安装驱动 sudo apt-get update sudo apt-get install ros-kinetic-xsens-driver 2.配置IMU 设置输出四元数,加速度、角速度、地磁 cd /opt/ros/kinetic/lib/xsens_driver python mtdevice.py --configure "oq,aa,wr,mf" 3.启动IMU roslaunch xsens_driver xsens_driver.launch 转(https://www.cnblo

qq_41585680的博客 2332

LeetCode Algorithm 0058 - Length of Last Word (Easy)

0058 - Length of Last Word (Easy),Related Topics: String

DarkRabbit的专栏 315

第55篇:数据隐私保护技术盘点——差分隐私、同态加密与它们的坑(踩坑总结)

数据隐私保护是AI工程化中必须严肃对待的课题。差分隐私和同态加密是两把利器,但也都是“重武器”,使用不当反而会伤及自身。差分隐私像“模糊处理”,通过加噪来保证统计安全性,要小心管理隐私预算和效用权衡。同态加密像“保险箱里打算盘”,保证了计算的精确性,但必须承受巨大的性能和工程复杂度代价。我的建议是:从小规模实验开始,先用DP-SGD在MNIST/CIFAR-10等标准数据集上感受噪声与精度的关系;再用TenSEAL等易用的库尝试一个加密逻辑回归,体会密文膨胀和速度延迟。

ai_blue_pm的博客 292

leetcode-58. Length of Last Word最后一单词的长度 python

Length of Last Word题目python split分割遍历 题目 Given a string s consists of upper/lower-case alphabets and empty space characters ’ ', return the length of last word (last word means the last appearing word if we loop from left to right) in the string. If the la

。 229

AI Agent开发第85课-DeepSeek-OCR 安装全指南:从 Transformers 到 vLLM,手把手教你跑通企业级 OCR

本文系统讲解 DeepSeek-OCR 的两种部署方式——基于 Hugging Face Transformers 的标准推理与基于 vLLM 的高性能加速推理。详细说明 CUDA 与 PyTorch 版本匹配、环境验证、依赖安装等关键细节,并提供可直接运行的完整代码示例。无论你是单卡调试还是高并发服务部署,都能在这里找到清晰路径。

打造全国最全的AI Agent开发知识领域的博客 2553

YOLOv8 + FireNet 火焰与烟雾检测系统开发指南:算法实现与前端 UI 展示详解

的FireNet火焰与烟雾检测系统,会是你毕设的“王牌项目”。它能实时检测视频流中的火焰与烟雾,还能实现图形界面可视化,从技术深度到成果展示都能让你在答辩中脱颖而出。界面会调用摄像头实时检测火焰与烟雾,检测结果会以带边界框的形式展示,同时给出“检测到火焰/烟雾!无论是学术创新性,还是在工业安防、建筑消防等场景的应用潜力,它都能让你的毕设极具说服力。传统人工监控效率低、易漏检,而基于YOLOv8的自动检测系统能实时识别火焰、烟雾,为火灾预警争取宝贵时间。火灾预防与应急响应是安全领域的核心需求,

know_F0727的博客 78

58. Length of Last Word

题目地址:https://leetcode.com/problems/length-of-last-word/description/Given a stringsconsists of upper/lower-case alphabets and empty space characters' ', return the length of la...

aodubi0638的博客 90

基于STM32L4XX、HAL库的DP83822 以太网收发器(PHY)驱动程序设计

一、简介:DP83822是德州仪器(TI)推出的一款低功耗、高性能10/100Mbps以太网物理层收发器(PHY)。它具有以下主要特性:支持10BASE-T和100BASE-TX以太网标准低功耗设计,适合嵌入式应用MII/RMII接口,方便与微控制器连接内置自检和诊断功能支持自动协商和手动配置工业级温度范围(-40°C至+85°C)

zhusl6688的博客 558

【LeetCode with Python】 Length of Last Word

Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string. If the last word does not exist, return 0. Note: A word is defined as a character sequence consists of non-space charact

XNERV SURVEYS 9910

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

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

WINCC7.3破解文件

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

【LeetCode】58. Length of Last Word

58. Length of Last Word Introduce Given a string s consists of upper/lower-case alphabets and empty sp...

roguesir的博客 817

深度学习工具包 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】Length of Last Word

题目链接:https://leetcode.com/problems/length-of-last-word/ 题目: Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the st

业精于勤,荒于嬉 1623

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

LeetCode-Length of Last Word

作者:disappearedgod 文章出处:http://blog.csdn.net/disappearedgod/article/details/23621903 时间:2014-8-27

上帝已逝,自求多福 775

leetcode 58. Length of Last Word

一 题目 Given a stringsconsists of upper/lower-case alphabets and empty space characters' ', return the length of last word in the string. If the last word does not exist, return 0. Note:A word is...

bohu83的博客 276

LeetCode58 Length of Last Word

详细见:leetcode.com/problems/length-of-last-word Java Solution: github package leetcode; public class P058_LengthOfLastWord { public static void main(String[] args) { System.out.println(new S

zxwtry的博客 359

leetcode python3 简单题58. Length of Last Word

1.编辑器 我使用的是win10+vscode+leetcode+python3 环境配置参见我的博客: 链接 2.第五十八题 (1)题目 英文: Given a string s consists of upper/lower-case alphabets and empty space characters ’ ', return the length of last word (last w...

从此做一个俗人 299

[LeetCode] Length of Last Word

[Problem] Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string. If the last word does not exist, return 0. Note: A word

1.02^365的成长裂变 3636

【leetcode c++】58 Length of Last Word

Length of Last Word Given a string s consists ofupper/lower-case alphabets and empty space characters ' ', return the length oflast word in the string. If the last word does not exist, return 0.

lif的博客 443

记录Leetcod第十天(58. Length of Last Word)+ stringstream

记录Leetcod第十天(58. Length of Last Word)+ stringstream 1.题目 Given a string s consists of upper/lower-case alphabets and empty space characters ’ ', return the length of last word in the string. If the la...

qq_42472150的博客 166

leetcode Length of Last Word

题目连接 https://leetcode.com/problems/length-of-last-word/ Length of Last Word Description Given a string s consists of upper/lower-case alphabets and empty space characters ’ ‘, return the le...

dong12276的博客 152

leetcode:字符串之Length of Last Word

leetcode:字符串之Length of Last Word 题目: Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string. If the last word does not

what_lei的博客 783
上一篇: 【算法】LeetCode算法题-Maximum Subarray
下一篇: LeetCode算法题-Plus One(Java实现)
程序员小川
博客等级 码龄10年 47粉丝 305原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值