58 - Length of Last Word
2016-03-07 14:20
218 查看
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
Subscribe to see which companies asked this question
思路分析:
此题较容易,有两个注意点。
1、int len = strlen(str); VS会报 不能将参数 1 从“std::string”转换为“const char *”解决 错。解决方法:std::string类有一个方法叫c_str()就是取出string对象的字符串,实现到char *的转换,调用方法:strlen(str.c_str());
2、注意以空格结尾的字符串。
' ', 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.
Subscribe to see which companies asked this question
思路分析:
此题较容易,有两个注意点。
1、int len = strlen(str); VS会报 不能将参数 1 从“std::string”转换为“const char *”解决 错。解决方法:std::string类有一个方法叫c_str()就是取出string对象的字符串,实现到char *的转换,调用方法:strlen(str.c_str());
2、注意以空格结尾的字符串。
class Solution { public: int lengthOfLastWord(string s) { int sz = strlen(s.c_str()); if (sz == 0) { return 0; } int res = 0; for (int i = sz - 1; i >= 0; i--) { if (s[i] != ' ') { res++; } //不能 else break 如果结尾时以空格开头的情况 else { if (res > 0) { return res; } } } return res; } };
相关文章推荐
- Backbone源码解析(六):观察者模式应用
- 如何扩大VMWARE的虚拟硬盘
- MVC的优缺点
- 上古格的路径查询,note
- thread线程,UI线程与后台线程,后台线程把message通过handler传给UI线程
- Spring <context:annotation-config/> 解说
- GPUImage写双输入的滤镜
- VIM文本替换命令
- Android项目:手机安全卫士(6)—— 手机防盗设置向导(二)
- 【Xamarin挖墙脚系列:Android最重要的命令工具ADB】
- 【Xamarin挖墙脚系列:对设备/模拟器的查看调试监听】
- 50个实用的jQuery代码段让你成为更好的Web前端工程师
- python的whl文件安装
- 老鸟是怎样炼成的!(摘抄自一位JAVA前辈,写的很好。)
- JAVA的Date类与Calendar类【转】
- Masonry设置右边距
- 【Xamarin挖墙脚系列:最重要的布局ListView】
- 【Xamarin挖墙脚系列:如何从一个Apk程序转化为Xamarin的程序】
- android 仿EF看视频弹出练习功能
- 一探究竟:box-sizing