[LeetCode]38. Length of Last Word最后单词长度
2015-10-24 18:16
441 查看
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
解法1:对输入字符串从后往前扫描,先去掉末尾空格得到输入字符串的“真正”end,然后找到第一个空格位置i,两个index之间即为最后一个单词,返回其长度即可。
解法2:另一个思路是先对输入字符串预处理,去掉开头和结尾多余的空格,然后从前往后扫描,遇到空格将计数器置零,否则计数器自增。这样计数器记录的自然就是最后一个单词的长度。
' ', 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.
解法1:对输入字符串从后往前扫描,先去掉末尾空格得到输入字符串的“真正”end,然后找到第一个空格位置i,两个index之间即为最后一个单词,返回其长度即可。
class Solution { public: int lengthOfLastWord(string s) { int n = s.size(), end = n - 1; int i = n - 1, j = n - 2; if (n == 0) return 0; for (; i >= 0; --i) { if (i == n - 1 && s[i] == ' ') { while (s[j] == s[j + 1]) --j; if (j < 0) return 0; i -= end - j; end = j; } if (s[i] == ' ') return end - i; } return end - i; } };
解法2:另一个思路是先对输入字符串预处理,去掉开头和结尾多余的空格,然后从前往后扫描,遇到空格将计数器置零,否则计数器自增。这样计数器记录的自然就是最后一个单词的长度。
class Solution { public: int lengthOfLastWord(string s) { int n = s.size(), count = 0; int left = 0, right = n - 1; while (left < n && s[left] == ' ') ++left; while (right >= 0 && s[right] == ' ') --right; for (int i = left; i <= right; ++i) { if (s[i] != ' ') ++count; else count = 0; } return count; } };
相关文章推荐
- poj 1656 Counting Black 水题
- 沉浸式状态栏
- codeforces 7C 【扩展欧几里得算法】
- xml约束技术之dtd
- JavaScript
- Hive简单介绍
- HDU1269:迷宫城堡【强连通】
- Unity3D--学习太空射击游戏制作(三)
- 暖
- 通过注释省略findviewbyid
- cf 3a Shortest path of the king
- 安卓开发中的小错误
- [实战]MVC5+EF6+MySql企业网盘实战(7)——文件上传
- poj 1410 Intersection 【判断线段 与矩形面是否相交】
- webpy 入门
- webpy 入门
- JavaScript函数基础
- 【ThinkingInC++】53、构造函数,析构函数,全局变量
- linux下nginx日志切割
- 从机器学习谈起