77. Length of Last Word
2016-05-21 22:59
375 查看
58. Length of Last Word
Total Accepted: 94158 Total Submissions: 319690 Difficulty: EasyGiven 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 n=s.size(); if(n==0)return 0;//为空返回0 int fir,sec=n-1; while(sec>=0&&s[sec]==' ')--sec;//从面找到倒数第一个不为空的字符 if(sec<0)return 0; //如果-1,说明没有不为空的 else fir = sec-1; while(fir>=0&&s[fir]!=' ')--fir;//找到该单词第一个字符 return sec-fir; //返回长度 } };
相关文章推荐
- 1010. 一元多项式求导 (25)
- 伙伴算法
- c语言实例之数列排序
- elasticsearch插件三—— Marvel插件安装详解
- 游戏网络测试基础
- java 微信开发
- c# 极验验证识别
- Unity3D 之UGUI 图片
- [Design Pattern] Mediator Pattern 简单案例
- 教你区分LVDS屏线及屏接口定义
- 配置ipvsadm服务
- 游戏测试基础知识
- cin、cin.get()、cin.getline()、getline()、gets()等函数的用法
- JavaBean
- 使用Gson解析泛型类型
- 4.html5中超链接
- elasticsearch插件二—— kibana插件安装详解
- java 网络编程(Socket) TCP/UDP 总结案例
- linux下mysql的root密码忘记解决方法
- 《构建之法》心得体会