当前位置:网站首页>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; }
边栏推荐
- MYSQLg advanced ------ clustered and non-clustered indexes
- 机器学习中什么是集成学习?
- 电商项目——商城限时秒杀功能系统
- En-us is an invalid culture error solution when Docker links sqlserver
- Audio codec, using FAAC to implement AAC encoding
- typedef defines the structure array type
- Interchangeability and Measurement Techniques - Tolerance Principles and Selection Methods
- Multi-merchant mall system function disassembly 26 lectures - platform-side distribution settings
- Echart地图的省级,以及所有地市级下载与使用
- Uni - app - access to Chinese characters, pinyin initials (according to the Chinese get pinyin initials)
猜你喜欢
【FPGA】day21-移动平均滤波器
【FPGA】SDRAM
机器学习可以应用在哪些场景?机器学习有什么用?
DNS分离解析和智能解析
分布式和集群的区别和联系
Binary tree related code questions [more complete] C language
QueryDet:级联稀疏query加速高分辨率下的小目标检测
Interchangeability and Measurement Techniques - Tolerance Principles and Selection Methods
互换性与测量技术-公差原则与选用方法
AI+Medical: Using Neural Networks for Medical Image Recognition and Analysis
随机推荐
云平台下ESB产品开发步骤说明
Leetcode 108. 将有序数组转换为二叉搜索树
The "top pillar" slides, and new growth is extremely difficult to shoulder the heavy responsibility. Is Ali "squatting" to jump higher?
常见布局效果实现方案
typedef defines the structure array type
What are port 80 and port 443?What's the difference?
When EasyCVR is connected to the GB28181 device, what is the reason that the device is connected normally but the video cannot be played?
多商户商城系统功能拆解26讲-平台端分销设置
获取链表长度
js 将字符串作为js执行代码使用
学编程的第十三天
索引的创建、查看、删除
【FPGA】day21- moving average filter
【FPGA】day22-SPI协议回环
UNI-APP_iphone bottom safe area
App Basic Framework Construction丨Log Management - KLog
What has programmatic trading changed?
【LeetCode】Day112-repetitive DNA sequence
UNI-APP_iphone苹果手机底部安全区域
Getting Started with Raspberry Pi (5) System Backup