LeetCode *** 58. Length of Last Word
2016-04-10 11:00
477 查看
题目:
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
分析:
如果有一个单词,那么必定是以‘空格+符号’的形式开始单词或者整个字符串都是一个单词的形式存在的。那么直接判断最后一次出现这种形式是什么时候即可。
代码:
合在一起:
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.
分析:
如果有一个单词,那么必定是以‘空格+符号’的形式开始单词或者整个字符串都是一个单词的形式存在的。那么直接判断最后一次出现这种形式是什么时候即可。
代码:
class Solution { public: int lengthOfLastWord(string s) { int length=s.length(); if(length==0)return 0; int last=0; int i; for(i=1;i<length;++i) if(s[i]!=' '&&s[i-1]==' '){ last=i; } i=last; int res=0; while(s[i]!=' '&&i<length){ res++;i++; } return res; } };
合在一起:
class Solution { public: int lengthOfLastWord(string s) { int length=s.length(); if(length==0)return 0; int last=0,res=0,lastI=last; for(int i=1;i<length;++i){ if(s[lastI++]!=' ')res++; if(s[i]!=' '&&s[i-1]==' '){ last=i; lastI=last; res=0; } } if(s[length-1]!=' ')res++; return res; } };
相关文章推荐
- PickerView的开源依赖
- 通过JDBC访问MySql数据库
- 注冊成为Windows Phone开发人员而且解锁Windows Phone 8.1手机
- 关于MYSQL表记录字段换行符回车符处理
- 集合之ArrayList
- 设计模式 (4)类图一
- 《LeetBook》leetcode题解(7): Reverse Integer[E]——处理溢出的技巧
- python核心模块之pickle和cPickle解说
- 冒泡排序
- Java空字符串与null的区别和判断字符串是否为空的方法
- PHP文件处理的高级应用
- 关于 boudingRectWithSize:options:attributes:context 说明
- python 字符串和整数的转换
- 网卡混杂模式
- php输出echo、print、print_r、printf、sprintf、var_dump比较
- MaterialDesign之NavigationView和DrawerLayout实现侧滑菜单栏
- 递归和闭包的理解
- opencl:C++11下使用别名(x,y,z,hi,lo...)访问vector类型(cl_int2,cl_long16...)的元素
- 响应式布局设计指南和教程(1)--响应式时代的设计历程
- countif