【一天一道LeetCode】#58. Length of Last Word
2016-05-23 20:25
309 查看
一天一道LeetCode系列
(一)题目
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.
(二)解题
题目比较简单,从尾向头找,第一个不为空格的字母,然后再继续找遇到空格为止。纪录单词长度。class Solution { public: int lengthOfLastWord(string s) { if(s.length() == 0) return 0; int count = 0; int i = s.length()-1; while(s[i]==' ') i--;//忽略前面的空格 while(i>=0&&s[i]!=' ') //当为字母的时候计算长度,为空格就退出循环 { count++; i--; } return count; } };
相关文章推荐
- 【一天一道LeetCode】#58. Length of Last Word
- PL/SQL如何调试Oracle存储过程
- java中文乱码问题----常见编码类型
- 119. Pascal's Triangle II
- Qt中文手册 之 QTableWidget
- 第十三周项目-4-立体族类共有的抽象类
- 注册--审核--登录 例题
- 欢迎使用CSDN-markdown编辑器
- html转pdf 下载操作
- 【定位技术】:常见的定位技术
- 5种网络I/O模型
- Angular的问题【学习angular的,建议看看】
- linux文件权限
- CodeForces 611C New Year and Domino (动态规划,DP)
- MySql的Date函数
- HBase Rowkey的散列与预分区设计
- Qt中文手册 之 QApplication
- 在Windows阅读Caffe代码
- Linux操作系统安装nginx
- Why fastjson so fast?