LeetCode:Length of Last Word
2015-08-24 17:13
561 查看
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
这个简单的题目花了不少时间,各种出错。后来发现“a ”通过不了,最后在for循环之前加了一个while先去掉最后的空格 通过。
class Solution {
public:
int lengthOfLastWord(string s) {
int num=0;
if (s.length()) {
int r = s.length()-1;
while (s[r]==' ') {
r--;
}
for ( ; r>=0; r--) {
if(s[r]==' '){
break;
}
num++;
}
}
return num;
}
};
' ', 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.
这个简单的题目花了不少时间,各种出错。后来发现“a ”通过不了,最后在for循环之前加了一个while先去掉最后的空格 通过。
class Solution {
public:
int lengthOfLastWord(string s) {
int num=0;
if (s.length()) {
int r = s.length()-1;
while (s[r]==' ') {
r--;
}
for ( ; r>=0; r--) {
if(s[r]==' '){
break;
}
num++;
}
}
return num;
}
};
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- Android之获取手机上的图片和视频缩略图thumbnails
- android string.xml文件中的整型和string型代替
- Android java 与 javascript互访(相互调用)的方法例子
- 关于指针的一些事情
- android上改变listView的选中颜色
- String.intern
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- Prototype源码浅析 String部分(二)
- Ruby中的String对象学习笔记
- Lua中调用C++函数示例
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(二):C++和Lua相互传递数据示例
- PostgreSQL ERROR: invalid escape string 解决办法
- C++联合体转换成C#结构的实现方法
- C++编写简单的打靶游戏
- C++ 自定义控件的移植问题
- C++变位词问题分析
- C/C++数据对齐详细解析