当前位置:网站首页>LeetCode 58. 最后一个单词的长度
LeetCode 58. 最后一个单词的长度
2022-07-04 14:01:00 【Tianchao龙虾】
LeetCode 58. 最后一个单词的长度
题目链接: https://leetcode.cn/problems/length-of-last-word/
给你一个字符串 s,由若干单词组成,单词前后用一些空格字符隔开。返回字符串中 最后一个 单词的长度。
单词 是指仅由字母组成、不包含任何空格字符的最大子字符串。
示例 1:
输入:s = “Hello World”
输出:5
解释:最后一个单词是“World”,长度为5。
题目解法:
class Solution {
public:
int lengthOfLastWord(string s) {
if(s.empty()) return 0;
const int size = s.size();
int count{
};
for (size_t i=size; i>0; --i){
// 减一表示去掉字符串最后的一个字符。
if(s[i-1] == ' '){
if(count > 0) break;
count = 0;
}else{
count ++;
}
}
return count;
}
};
题目笔记:
反向遍历,累计长度。但需要注意的是字符串最后有一个隐藏的字符,因此需要-1。本质 '\0’是字符串结束标志,不计入串长,但要占内存空间。这里和一张二值图片中,找一行连续的像素有异曲同工之妙。 即遍历一行的像素,如果满足连续多少个像素,则返回开始像素,结束像素,还有对应的行。
边栏推荐
- 韩国AI团队抄袭震动学界!1个导师带51个学生,还是抄袭惯犯
- 微博、虎牙挺进兴趣社区:同行不同路
- [local differential privacy and random response code implementation] differential privacy code implementation series (13)
- 智能客服赛道:网易七鱼、微洱科技打法迥异
- Kubernets pod exists finalizers are always in terminating state
- web聊天室实现
- 宽度与对齐
- Ali was laid off employees, looking for a job n day, headhunters came bad news
- 对话龙智高级咨询顾问、Atlassian认证专家叶燕秀:Atlassian产品进入后Server时代,中国用户应当何去何从?
- 十六进制
猜你喜欢
Memory management summary
03-存储系统
Redis 發布和訂閱
C1 certification learning notes 3 -- Web Foundation
MP3是如何诞生的?
[C language] Pointer written test questions
Korean AI team plagiarizes shock academia! One tutor with 51 students, or plagiarism recidivist
微博、虎牙挺进兴趣社区:同行不同路
UFO: Microsoft scholars have proposed a unified transformer for visual language representation learning to achieve SOTA performance on multiple multimodal tasks
Helix Swarm中文包发布,Perforce进一步提升中国用户体验
随机推荐
UFO: Microsoft scholars have proposed a unified transformer for visual language representation learning to achieve SOTA performance on multiple multimodal tasks
03 storage system
How to build a technical team that will bring down the company?
深度学习 神经网络的优化方法
文本挖掘工具的介绍[通俗易懂]
UFO:微软学者提出视觉语言表征学习的统一Transformer,在多个多模态任务上达到SOTA性能!...
自动控制原理快速入门+理解
I plan to teach myself some programming and want to work as a part-time programmer. I want to ask which programmer has a simple part-time platform list and doesn't investigate the degree of the receiv
The performance of major mainstream programming languages is PK, and the results are unexpected
左右对齐!
selenium 元素交互
ES6 modularization
Helix Swarm中文包发布,Perforce进一步提升中国用户体验
%s格式符
Weibo and Huya advance into interest communities: different paths for peers
LeetCode 1200 最小絕對差[排序] HERODING的LeetCode之路
产品好不好,谁说了算?Sonar提出分析的性能指标,帮助您轻松判断产品性能及表现
Redis的4种缓存模式分享
How to match chords
Five minutes per day machine learning: use gradient descent to complete the fitting of multi feature linear regression model