Length of Last Word
来源:互联网 发布:56式军装淘宝 编辑:程序博客网 时间:2024/06/15 16:07
这个没什么技术含量,从后往前扫,然后注意处理,最后都是空格的情况......我写的就很啰嗦,还立了一个flag......
class Solution {public: int lengthOfLastWord(string s) { int n=s.size(); int flag=0; if(s.empty()) return 0; for(int i=n-1;i>=0;i--) { if(s[i]!=' '&&flag==0) { flag=1; n=i+1; } else if(s[i]==' '&&flag==1) { return n-i-1; } } if(flag==1) return n; else return 0; }};
然后别人家的代码,思路一样从后往前扫,然而......明白很多
class Solution {public: int lengthOfLastWord(string s) { int len = 0, tail = s.length() - 1; while (tail >= 0 && s[tail] == ' ') tail--; while (tail >= 0 && s[tail] != ' ') { len++; tail--; } return len; }};
0 0
- Length of Last Word
- Length of Last Word
- Length of Last Word
- Length of Last Word
- Length of Last Word
- Length of Last Word
- Length of Last Word
- Length of Last Word
- Length of Last Word
- Length of Last Word
- Length of Last Word
- Length of Last Word
- Length of Last Word
- Length of Last Word
- Length of Last Word
- Length of Last Word
- Length of Last Word
- Length of Last Word
- android studio使用WebView提示net ERR_FILE_NOT_FOUND
- 突然想起以前的日子
- 大数据学习-Spark前世今生
- [leetcode][18]4Sum
- laravel 队列的驱动配置
- Length of Last Word
- 【JavaEE—Hibernate】hql查询简介
- J2EE开发时的包命名规则,养成良好的开发习惯
- LeetCode 453. Minimum Moves to Equal Array Elements
- js事件委托(事件代理)
- 矩阵的秩探究
- 设备驱动中的mutex(kernel-4.7)
- 飞机游戏移动和发射子弹的小模型
- hibernate延迟加载(get和load的区别)