Length of Last Word(返回最后一个字母的长度)
2015-08-01 18:23
316 查看
题目描述:
Given a string s consists of upper/lower-case alphabets and empty space characters
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 =
return
思路:
返回最后一个单词的长度,从后遍历整个字符串,遇到空格跳出,不遇到空格,变量加1.
代码实现:
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.
思路:
返回最后一个单词的长度,从后遍历整个字符串,遇到空格跳出,不遇到空格,变量加1.
代码实现:
class Solution { public: int lengthOfLastWord(string s) { int len=s.length(); int i=len-1; int j=0; while(i>=0 && s[i]==' ') { i--; } while(i>=0 && s[i]!=' ') { i--; j++; } return j; } };
相关文章推荐
- HDU1299 素数分解
- HDOJ 1795 The least one(素数打表)
- IOS开发UI基础文本属性Attributes
- 使用innotop监测mysql
- HashMap解决hash冲突的方法
- vs2010 和 vs2012同时安装遇到的问题
- C语言关键字详解
- IOS开发UI基础UIControl事件
- Appium for Mac 环境准备篇
- (个人开源)ffpanel --ffmpeg的GUI,让ffmpeg离开黑黑的命令行
- POJ 2828 Buy Tickets 线段树
- IOS开发UI基础UIImagePickerController的属性
- 小点滴——Lingo的非线性规划、最优化求解
- HDU杭电4883 TIANKENG’s restaurant
- 你们信不信一句Console.WriteLine就能让你的控制台程序失去响应
- winscp和putty提取固件教程
- CentOS6.5 安装配置drbd
- poj 3461 Oulipo kmp字符串匹配
- Juniper srx防火墙NAT配置
- CooMark网页颜色取色表