58. Length of Last Word
来源:互联网 发布:新浪微博白菜淘宝客 编辑:程序博客网 时间:2024/04/29 05:53
<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">这道题乍一看很简单,其实还是得稍微有一点点弯弯绕的。主要是边界条件特殊的case比较多。</span>
需要注意到几点:
1. leading space
2. tailing space
3. 整个string全是空格
4. 单词之前好多空格
第一种解法是从前向后扫一遍,没遇到一个空格,记录下位置再继续找下一个空格知道字符串结束。这种方法需要去掉leadig/tailing空格。写起来有一点点繁琐。
class Solution {public: int lengthOfLastWord(string s) { if(s.size()==0) return 0; int p=0, q=0, len=s.size()-1; while(q<s.size()&&s[q]==' '){ q++; } q--; while(len>=0&&s[len]==' '){ len--; } len++; while(p<len){ if(s[p]==' '){ q=p; } p++; } return (p-q-1)<0?0:p-q-1; }};
第二种解法就是从后向前,只用去除最后面的tailing space,写起来稍微见大一些。
class Solution {public: int lengthOfLastWord(string s) { int q=s.size()-1; int res=0; while(q>=0&&s[q]==' '){ q--; } while(q>=0&&s[q]!=' '){ res++; q--; } return res; }};这种题主要还是要注意spacial case,看到简单题不能太激动,肯定有坑。
0 0
- 58. Length of Last Word
- 58. Length of Last Word
- 58. Length of Last Word
- 58. Length of Last Word
- 58. Length of Last Word
- 58. Length of Last Word
- 58. Length of Last Word
- 58. Length of Last Word
- 58. Length of Last Word
- 58. Length of Last Word
- 58. Length of Last Word
- 58. Length of Last Word
- 58. Length of Last Word
- 58. Length of Last Word
- 58. Length of Last Word
- 58. Length of Last Word
- 58. Length of Last Word
- 58.Length of Last Word
- win32程序中调用控制台程序
- 批量检查代理ip是否可用 curl-multi php检测ip代理是否有效
- 【Leetcode】8.String to Integer (atoi) 解题
- MySQL没有 data 目录的解决方法或者重建 data 目录
- Remove the duplicates from sorted array
- 58. Length of Last Word
- 152. Maximum Product Subarray
- azure 云端centos6.5下oracle11g服务开机自启动
- Swift快速入门之对象和类
- remove duplicate from sort array 2
- 未来的趋势
- [soft ability]什么才算是真正的编程能力
- Fadora下载地址
- a毛 jquery 学习记 5 基础DOM和CSS操作3