LeetCode(59)Length of Last Word
来源:互联网 发布:博客助赢软件cpzyrj 编辑:程序博客网 时间:2024/04/29 23:55
题目
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.
分析
题目要求得出所给字符串最后一个单词的长度。
这其实是一个很简单的题目,主要有几个需要注意的点:
- 空字符串,自然是返回0
- 只有一个单词的字符串,返回长度即可
- 若是输入字符串为“hello “也就是说,最后是多个空字符时,返回的长度要求是最后非空字符组成的最后一个单词而不是0;
AC代码
class Solution {public: int lengthOfLastWord(string s) { int len = strlen(s.c_str()); //如果是空字符串或者是单字符,则直接返回长度 if (len == 0) return len; int i = len-1 , j = 0; //从后向前找到非空字符 while (i>=0 && s[i] == ' ') --i; for (j = i; j>=0 && s[j] != ' '; --j) ; return i - j; }};
GitHub测试程序源码
0 0
- LeetCode(59)Length of Last Word
- Length of Last Word (leetcode)
- LeetCode: Length of Last Word
- LeetCode Length of Last Word
- LeetCode : Length of Last Word
- [Leetcode] Length of Last Word
- [LeetCode] Length of Last Word
- [LeetCode]Length of Last Word
- [leetcode]Length of Last Word
- Leetcode:Length of Last Word
- LeetCode-Length of Last Word
- [LeetCode] Length of Last Word
- [leetcode] Length of Last Word
- leetcode length of last word
- LeetCode - Length of Last Word
- leetcode:Length of Last Word
- LeetCode:Length of Last Word
- LeetCode | Length of Last Word
- 去哪网实习总结:java读写excel表格(JavaWeb)
- Javascript将数字转为中文大写金额形式
- Django之第一个app<1>
- 【React】热热身:Hello World
- 2.5 寻找最大的k个数
- LeetCode(59)Length of Last Word
- 基本算法复习之排序:性能比较、代码分析
- JAVA基础(三)
- Eclipse JEE中tomcat配置
- 几种重要的倒序传值方式
- Xcode个人常用插件
- ios日期格式转换
- 利用辛达拉姆筛进行素数判定
- 在cocos2d-x中嵌入网页