LeetCode---(58)Length of Last Word
2015-07-10 14:58
459 查看
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) {
if(s.empty()==1)
return 0;
int last=s.size()-1,first=0;
while(s[last]==' '&&last>=0)
last--;
first=last;
while(s[first]!=' '&&first>=0)
first--;
return last-first;
}
};
' ', 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 len=s.size(); if(len==0) return 0; int res=0; int i=0; while(i!=len) { if(s[i]!=' ') { int curlength=0; while(s[i]!='\0'&&s[i]!=' ') { curlength++; i++; } res=curlength; } else i++; } return res; } };
使用以上的算法可以解决求字符串内单词的多种变形,下边的算法,从后边开始遍历,更加简单
class Solution {
public:
int lengthOfLastWord(string s) {
if(s.empty()==1)
return 0;
int last=s.size()-1,first=0;
while(s[last]==' '&&last>=0)
last--;
first=last;
while(s[first]!=' '&&first>=0)
first--;
return last-first;
}
};
相关文章推荐
- CSS3 3D transform变换
- AFNetworking、MKNetworkKit和ASIHTTPRequest对比
- android的四种加载模式
- java按指定编码写入和读取文件内容的类
- SQL语句实现模糊查询
- LintCode UniquePathsII 不同的路径II
- 使用Quick-Cocos2d-x开发植物大战僵尸02-地图编辑
- mongodb进阶三之mongodb管理
- WCF技术剖析之十九:深度剖析消息编码(Encoding)实现(上篇)
- WCF技术剖析之十八:消息契约(Message Contract)和基于消息契约的序列化
- Python学习笔记三:函数
- Codeforces Beta Round #96 (Div. 1) C. Logo Turtle (DP)
- 正则表达式基本语法
- sdl
- Hibernate 常见异常
- O2O竞争加速 百度外卖将完成2亿美元融资
- IOS6.0 应用内直接下载程序 不需跳转AppStore
- html 如何绑定radio 控件和label控件
- WCF技术剖析之十七:消息(Message)详解(下篇)
- 附加到进程 调试技巧--【VS】