leetcode:Length of Last Word
来源:互联网 发布:如何查询淘宝店铺排名 编辑:程序博客网 时间:2024/04/29 03:56
一、 题目
给定一个字符串s由大/小写字母和空的空间字符' ',返回字符串的最后一个单词的长度。
如果最后一个单词不存在,则返回0。
注:一个单词被定义为一个不带空格的字符序列。
例如,
给出s =“Hello World”,
返回5。
二、 分析
没有什么复杂的算法,按照规则考虑所有情况就行,有下面的几种情况:
1、“ ”
2、“abc”
3、“ abc”
4、“abc ”
我使用了两种方法,
1、从左到右扫描,首先过滤前面的空格,扫描符合的字符数,再判空或尾部,并把当前的有效长度保存,如果后面还有有效的字符,那么就更新这个值。
class Solution {public: int lengthOfLastWord(const char *s) { int count = 0; int i = 0; int last = 0; while(s[i] != '\0'){ while(s[i] == ' ') i++; if(s[i] == '\0') return last; while(s[i] != ' '&& s[i] != '\0'){ count++; i++; } if(s[i] == '\0') return count; last = count; count = 0; } return last; }};
2、求出字符串长度,从右往左扫描,此时只需要找到第一个单词长度即可。
class Solution {public: int lengthOfLastWord(const char *s) { int len = strlen(s) - 1; int count = 0; while(len >= 0 && s[len] == ' ') len --; while(len >= 0 && s[len] != ' '){ count++; len--; } return count; }};
0 0
- LeetCode: Length of Last Word
- LeetCode Length of Last Word
- LeetCode : Length of Last Word
- [Leetcode] Length of Last Word
- [LeetCode] Length of Last Word
- [LeetCode]Length of Last Word
- [leetcode]Length of Last Word
- Leetcode:Length of Last Word
- LeetCode-Length of Last Word
- [LeetCode] Length of Last Word
- [leetcode] Length of Last Word
- leetcode length of last word
- LeetCode - Length of Last Word
- leetcode:Length of Last Word
- LeetCode:Length of Last Word
- LeetCode | Length of Last Word
- LeetCode - Length of Last Word
- Leetcode: Length of Last Word
- Leetcode: Remove Element
- ASP操作数据库常用入门级代码
- POJ 3735 Training little cats (矩阵快速幂)
- 又一版 A+B
- 2014成为了过去,2015继续向前
- leetcode:Length of Last Word
- Makefile 中:= ?= += =的区别
- Leetcode: Implement strStr()
- 博弈问题之三大博弈
- linux 安装XEN
- socket编程
- 数学之路-sas备忘(3)
- 1033_旧键盘打字(20)
- leetcode-set Matrix Zero