【算法】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 小结

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

国内用户稳定开通ChatGPT Plus会员的完整实操指南 ChatGPT作为当前最先进的AI对话模型,其技术原理基于Transformer架构和大规模语言预训练。通过深度学习技术,ChatGPT能够理解自然语言并生成高质量回复,在代码生成、文档分析等场景具有重要技术价值。对于需要高频使用的开发者而言,ChatGPT Plus会员提供了优先访问权和GPT-4模型支持等核心功能。在实际应用场景中,国内用户常面临支付限制和区域封锁等挑战。本文针对这些痛点,重点解析如何通过可靠的支付渠道和账号安全策略,实现稳定的会员开通方案,帮助用户突破技术使用壁垒,充分发挥AI助手在开 阅读详情

相关推荐

在Window上安装和配置VTK9.x,并在QT项目中调试VTK是否可用

VTK+MSVC+Qt Creator + CMake配置

qq_42279379的博客 1000

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

嵌入式环境下XML配置文件解析实践

在资源受限的嵌入式环境中,如何轻量级地解析XML配置文件成为关键。通过简化语法结构与优化内存使用,实现快速读取和解析配置文件,提升系统启动效率与稳定性。

weixin_31869917的博客 401

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的专栏 379

Matlab实战:3种雷达间歇采样干扰的仿真与识别(附完整代码)

本文通过Matlab实战,详细仿真了雷达有源间歇采样干扰的三种核心样式:直接转发、重复转发和循环转发干扰。文章提供了完整的代码实现,并深入探讨了基于时频分析和循环平稳分析的特征提取与识别方法,为雷达抗干扰技术的学习与实践提供了清晰的工程实现路径。

weixin_29053695的博客 364

贝塞尔曲线基础

贝塞尔曲线于1962年由法国工程师皮埃尔·贝塞尔(Pierre Bézier)所广泛发表,他运用贝塞尔曲线来为汽车的主体进行设计。贝塞尔曲线最初由Paul de Casteljau于1959年运用de Casteljau演算法开发,以稳定数值的方法求出贝兹曲线。

YiYeZhiNian的博客 2052

LeetCode Algorithm 0058 - Length of Last Word (Easy)

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

DarkRabbit的专栏 314

实现labelme批量json_to_dataset方法

labelme可以帮助我们快速的实现Mask-RCNN中数据集json文件的生成,然而还需要我们进一步的将json转成dataset,可以直接在cmd中执行labelme_json_to_dataset.exe C:\Users\Administrator\Desktop\total\1.json(路径),但是这个过程需要我们一个json文件的生成,过程很慢。 一、打开abelm...

简简单单 5万+

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

合肥工业大学操作系统实验9

依据操作系统课程所介绍的页面置换算法与动态内存分配的原理,本实验的目的是掌握OPT、FIFO、LRU、LFU、Clock等页面置换算法;掌握可用空间表及分配方法;掌握边界标识法以及伙伴系统的内存分配方法和回收方法。从而深入理解操作系统的内存管理。从而加深对教材上页面置换算法与动态内存分配的理解。

Martin-share的博客 1096

在armv8架构中,有哪些是serror

(3)、RAS(Reliability, Availability, and Serviceability)错误:一些对于系统的可靠性、可用性和可维护性有影响的错误可能会触发 SError。(2)、ECC(Error Correction Code)错误:在访问带有错误校验的内存(如ECC内存)时,如果发现错误校验失败,可能会产生SError。2、其实呢,大多数Serror都是实现定义的,真正实现的serror就没有多少个。Serror(也称System Error),是异步异常的一种,一般是来自。

baron-周贺贺-代码改变世界ctw 1013

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的博客 88

学Simulink——基于Simulink的超前-滞后校正控制器设计与仿真建模示例

本文完成了基于 Simulink 的超前-滞后校正控制器设计与仿真,实现了:✅掌握超前与滞后校正的物理意义与设计流程✅分步设计复合控制器,兼顾动态与稳态✅在 Simulink 中搭建闭环系统并验证卓越性能✅达成高稳定裕度、高精度、快速响应三大目标。

xiaoheshang_123的博客 81

【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 9909

怀旧版电脑GBC模拟器

再现原版GBC掌机的界面,电脑运行连游戏界面都一样大小,很怀旧,很真实,(英文版)强烈推荐,很小的文件,很难才找到的。

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

【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的博客 816

android 蓝牙通讯demo

android 下蓝牙通讯demo,实现了发现蓝牙,使能蓝牙,通过蓝牙发送消息。

【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

业精于勤,荒于嬉 1620

jdk-8u144-linux-x64.tar.gz.

该资源为搭建Linux系统Java环境用,资源的后缀为tar.gz格式的压缩包

LeetCode-Length of Last Word

作者:disappearedgod 文章出处:http://blog.youkuaiyun.com/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的博客 275

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

从此做一个俗人 298

[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的成长裂变 3635

【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的博客 150

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的博客 781
上一篇: 【算法】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、付费专栏及课程。

余额充值