58. Length of Last Word
2015-06-25 11:21
411 查看
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
从字符串的末尾往前遍历。
首先跳过空格。
然后对第一个连续非空格字符串中的字符个数计数。
class Solution {
public:
int lengthOfLastWord(string s) {
int i = s.length()-1;
int len = 0;
while(i>=0 && s[i] == ' ')
--i;
while(i>=0 && s[i] != ' ')
{
++len;
--i;
}
return len;
}
};
' ', 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) {
int i = s.length()-1;
int len = 0;
while(i>=0 && s[i] == ' ')
--i;
while(i>=0 && s[i] != ' ')
{
++len;
--i;
}
return len;
}
};
class Solution { public: int lengthOfLastWord(string s) { int retLen = 0; for(int i = 0;i< s.length();i++) { while(s[i] == ' ') i++; int curLen = 0; while(s[i] != ' ' && s[i] != '\0') { curLen++; i++; } if(curLen != 0) retLen = curLen; } return retLen; } };
相关文章推荐
- 12个优化MySQL的技巧小整理
- cocos2dx 实例 经典游戏机(一)
- Lucene学习总结之二:Lucene的总体架构(转载)
- Java后台实现方法
- 单例模式
- Binary Tree Right Side View
- hibernate多对多关联
- 一个手工删除mysql的sleep线程的小脚本
- Avaya收购Esna丰富企业通信应用
- 设计模式在Android中的运用
- Java Reflection(二):Classes
- 离线安装Cloudera Manager 5和CDH5(最新版5.1.3) 完全教程
- 实现一个数值加法函数,返回两个数字的和。要求能进行参数验证,若参数不是数字或为空则抛出异常。
- LeetCode_50---Pow(x, n)
- android fragment 延迟加载数据
- jQuery实现为图片添加镜头放大效果的方法
- 【9. Windows跳板机简述】 云跳板机服务系统设计及实现
- 编程之美之数独求解器的C++实现方法
- 树的基本运用三(线索二叉树)
- java使用UDP协议传输数据