[leetcode] 58.Length of Last Word
2015-08-31 17:31
375 查看
题目:
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.
题意:
给定一个字符串,包含大小写或者空格。
思路:
把字符串先反转,然后找第一个word的长度。
以上。
代码如下:
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.
题意:
给定一个字符串,包含大小写或者空格。
思路:
把字符串先反转,然后找第一个word的长度。
以上。
代码如下:
class Solution { public: int lengthOfLastWord(string s) { if(s.empty())return 0; int first = 0, second = s.length() - 1; while(first < second) { swap(s[first], s[second]); first++; second--; } first = 0; while(first < s.size() && s[first] == ' ')first++; second = first; while(second < s.size() && s[second] != ' ')second++; return second - first; } };
相关文章推荐
- Openssl简易安装
- LinuxCon 2015 亮点回顾
- Axure 7.0 快捷键及快速上手总结
- Android上调用ffmpeg的简单实例,附源码FFmpegTest
- 如何快速提高网站关键词排名(实战篇)
- php self this 区别
- Java核心API -- 13(线程)
- 理解 Linux 的硬链接与软链接
- MVC中bootstrap循环绑定数据源
- 《JAVA与模式》之适配器模式
- java 四舍五入保留小数
- Android混淆打包规范
- Android Canvas drawArc方法介绍
- unity3d调试心得
- mysql常用函数
- zvzvzv
- 为什么说中小企业更需要手机移动考勤办公?
- JSON简单用法
- Windows 2008 r2 防火墙设置端口例外的方法
- PCIE协议解析 synopsys IP 基本配置空间总结 读书笔记(14)