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 exist, return 0.
Note: A word is defined as a character sequence consists of non-space characters only.
For example,
Given s = "Hello World"
,
return 5
.
借助strlen函数,相当于遍历两遍字符串 本文地址
1 class Solution { 2 public: 3 int lengthOfLastWord(const char *s) { 4 if(s == NULL)return 0; 5 int len = strlen(s), i, res = 0; 6 for(i = len-1; i >= 0 && s[i] == ' '; i--);//从尾部开始找到第一个非空格字符 7 for(; i >= 0 && s[i] != ' '; i--)res++; 8 return res; 9 } 10 };
遍历一遍字符串
1 class Solution { 2 public: 3 int lengthOfLastWord(const char *s) { 4 if(s == NULL)return 0; 5 int res = 0, cnt = 0; 6 for(; *s != '\0'; s++) 7 { 8 if(*s == ' ') 9 { 10 if(cnt != 0) 11 res = cnt; 12 cnt = 0; 13 } 14 else cnt++; 15 } 16 return cnt == 0 ? res : cnt; 17 } 18 };
【版权声明】转载请注明出处:http://www.cnblogs.com/TenosDoIt/p/3722115.html
转载于:https://www.cnblogs.com/TenosDoIt/p/3722115.html
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 ...
- LeetCode Length of Last Word(最后一个单词的长度)
题意:给出一个字符串,其中包含大小写字母,空格,求其最后一个单词的长度 思路:将字符串以空格为分隔符,将其分割成字符串数组 代码如下: public class Solution {public in ...
- LeetCode刷题记录9——58. Length of Last Word(easy)
LeetCode刷题记录9--58. Length of Last Word(easy) 目录 LeetCode刷题记录9--58. Length of Last Word(easy) 题目 语言 思 ...
- leetcode python3 简单题58. Length of Last Word
1.编辑器 我使用的是win10+vscode+leetcode+python3 环境配置参见我的博客: 链接 2.第五十八题 (1)题目 英文: Given a string s consists ...
- LeetCode: 58. Length of Last Word
051101 题目 Given a string s consists of upper/lower-case alphabets and empty space characters ' ', re ...
- leetcode 58. Length of Last Word 题解【C++/Java/Python/JS】
58. 最后一个单词的长度 58. Length of Last Word 题目: 给定一个仅包含大小写字母和空格' ' 的字符串,返回其最后一个单词的长度. 如果不存在最后一个单词,请返回0 . 说 ...
- 【LeetCode从零单排】No58.Length of Last Word
题目 Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return th ...
- C#LeetCode刷题之#58-最后一个单词的长度(Length of Last Word)
问题 该文章的最新版本已迁移至个人博客[比特飞],单击链接 https://www.byteflying.com/archives/3927 访问. 给定一个仅包含大小写字母和空格 ' ' 的字符串, ...
- LeetCode 58. Length of Last Word
58. Length of Last Word My Submissions QuestionEditorial Solution Total Accepted: 90032 Total Submis ...
最新文章
- Android之ksoap2-android详解与调用天气预报Webservice完整实例
- Mocha BSM应用管理——Lotus Domino监控与管理
- Allegro16.6软件布局设计技巧:模块复用
- Visual Studio 2017 调试 windows server 2016 Docker Container
- 免费都不管用,Win10升级在中国怎么就这么难?
- LeetCode 496. 下一个更大元素 I(哈希)
- 转贴XML的写法建议
- 反病毒软件技术简析与探索(2009年5月18日)
- 装饰器模式在 Collections 类中的应用
- EXCEL下拉菜单怎么弄
- latex 箭头上带_latex 上下箭头
- 如何快速完成一份学术型PPT
- 2023电工杯数学建模A题思路模型代码
- 编译安装oh-my-zsh
- 极客时间《软件工程之美》学完感
- 从运维技术架构变化初探运维组织转型
- 目标检测系列论文汇总
- 微信小游戏开发学习记录
- 决策树模型之泰坦尼克号乘客是否生还预测
- 联表查询JOIN介绍