[leetcode] 58. Length of Last Word
来源:互联网 发布:水果网络营销策划书 编辑:程序博客网 时间:2024/05/16 08:22
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
.
解法一:
用std::reverse翻转string,然后打出第一个词。
class Solution {public: int lengthOfLastWord(string s) { if(s.size()==0) return 0; reverse(s.begin(),s.end()); istringstream in(s); string lastw; in>>lastw; return lastw.size(); }};
解法二:
主要是要先将末尾的空格跳过。
class Solution {public: int lengthOfLastWord(string s) { int right = s.size()-1; while(right>=0 && s[right]==' ') right--; int count = 0; while(right>=0 && s[right]!=' ') { right--; count++; } return count; }};
0 0
- 58. Length of Last Word Leetcode Python
- [LeetCode]58.Length of Last Word
- LeetCode --- 58. Length of Last Word
- [Leetcode] 58. Length of Last Word
- [leetcode] 58.Length of Last Word
- LeetCode - 58. Length of Last Word
- <LeetCode OJ> 58. Length of Last Word
- 58. Length of Last Word LeetCode
- 【LeetCode】58. Length of Last Word
- leetcode 58. Length of Last Word
- LeetCode *** 58. Length of Last Word
- LeetCode 58. Length of Last Word
- leetcode-58. Length of Last Word
- LeetCode-58.Length of Last Word
- [leetcode] 58. Length of Last Word
- LeetCode 58. Length of Last Word
- Leetcode-58. Length of Last Word
- leetcode-java-58. Length of Last Word
- 调用第三方的WS服务
- cocos2D从0到1之hello,cocos2D
- Pro JPA2读书笔记系列(四)-第四章(对象-关系映射)
- lfs 使用
- App Thinning研究
- [leetcode] 58. Length of Last Word
- 正则表达式
- 微信接口 图灵自动回复
- smarty2 foreach用法简单介绍
- SpringMVC的配置文件
- 浅析Java中的final关键字
- JavaScript中的闭包
- 今天开通博客吧
- 用R语言进行数据分析