当前位置:网站首页>LeetCode刷题第11天字符串系列之《 58最后一个单词长度》
LeetCode刷题第11天字符串系列之《 58最后一个单词长度》
2022-08-11 03:42:00 【小机double】
LeetCode 58最后一个单词长度
题目描述
给定一个仅包含大小写字母和空格 ’ ’ 的字符串 s,返回其最后一个单词的长度。如果字符串从左向右滚动显示,那么最后一个单词就是最后出现的单词。
如果不存在最后一个单词,请返回 0 。
说明:一个单词是指仅由字母组成、不包含任何空格字符的 最大子字符串。
示例
输入: “Hello World”
输出: 5
题目解析
按照题目的意思,反正就是找到最后一个有字母的单词的长度(当然拼写正不正确不是我们管的)。那么从后往前开始遍历,统计字符的个数,遇到空格的时候返回统计的长度即可。但是题目给的字符串可能在最后面会给出多个空格,例如:“hello world ”。此时只需将首尾的空格去掉即可。去掉方法有以下两种:
- 使用java字符串中的trim方法去掉首尾空格
- 不用显示去掉,直接在统计的时候跳过最后面的空格,遇到第一个不是空格的字符时开始计算。
下面是两种实现方式:
对于java,C++,python等这类语言的话,都有对于字符串的切片操作,即split。下面就是直接使用split函数,将输入的字符串根据空格切分成字符串数组,返回该数组最后一个字符串的长度即可。
public int lengthOfLastWord(String s) { String[] split = s.split(" "); if (split.length == 0) { //s都是空格的话切分之后的数组为空 return 0; } return split[split.length - 1].length(); }程序执行结果:

上面那种使用split的方法虽然简单直接,但是并没有那么快,直接从后面往前面统计的方法就要快很多,代码如下:
public int lengthOfLastWord(String s) { int count = 0; //s = s.trim(); //提前将首尾的空格去除掉 for (int i = s.length() - 1; i >= 0; i--) { if (s.charAt(i) == ' ' && count == 0) { //直接跳过末尾的空格,没有用trim方法的话可以这么实现 continue; } if (s.charAt(i) == ' ') { //跳过最末尾的所有空格后如果之后还出现空格则证明最后一个单词的长度已经统计完毕 break; } count++; } return count; }

边栏推荐
- C语言之自定义类型------结构体
- 【愚公系列】2022年08月 Go教学课程 035-接口和继承和转换与空接口
- 【FPGA】day22-SPI协议回环
- 【愚公系列】2022年08月 Go教学课程 036-类型断言
- Interchangeability Measurements and Techniques - Calculation of Deviations and Tolerances, Drawing of Tolerance Charts, Selection of Fits and Tolerance Classes
- 【ADI低功耗2k代码】基于ADuCM4050的ADXL363、TMP75的加速度、温度检测及串口打印、蜂鸣器播放音乐(孤勇者)
- 互换性测量技术-几何误差
- Leetcode 450. 删除二叉搜索树中的节点
- App基本框架搭建丨日志管理 - KLog
- The "top pillar" slides, and new growth is extremely difficult to shoulder the heavy responsibility. Is Ali "squatting" to jump higher?
猜你喜欢

移动端地图开发选择哪家?

树莓派入门(5)系统备份

Interchangeability and Measurement Technology—Surface Roughness Selection and Marking Method

你不知道的 console.log 替代品

什么是机器强化学习?原理是什么?

作业8.10 TFTP协议 下载功能

CTO said that the number of rows in a MySQL table should not exceed 2000w, why?

Is Redis old?Performance comparison between Redis and Dragonfly

二叉树相关代码题【较全】C语言

E-commerce project - mall time-limited seckill function system
随机推荐
console.log alternatives you didn't know about
rac备库双节点查询到的表最后更新时间不一致
Uni - app - access to Chinese characters, pinyin initials (according to the Chinese get pinyin initials)
互换性与测量技术——表面粗糙度选取和标注方法
C语言之自定义类型------结构体
C language recv() function, recvfrom() function, recvmsg() function
学编程的第十三天
【FPGA】设计思路——I2C协议
常见布局效果实现方案
Ten Advanced Concepts of SQL Development
多商户商城系统功能拆解26讲-平台端分销设置
浮点数在内存中的存储方式
[DB operation management/development solution] Shanghai Daoning provides you with an integrated development tool to improve the convenience of work - Orange
Qnet弱网测试工具操作指南
What has programmatic trading changed?
互换性测量技术-几何误差
高度塌陷问题的解决办法
The "top pillar" slides, and new growth is extremely difficult to shoulder the heavy responsibility. Is Ali "squatting" to jump higher?
pathman_config、pathman_config_params 删除后,如何重建?
阿里低代码框架 lowcode-engine 之自定义物料篇