54:Length of Last Word
2017-02-28 22:20
330 查看
题目: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 consist
解题代码一(从后往前扫描):
解题代码二(从前往后扫描):
Note: A word is defined as a character sequence consist
解题代码一(从后往前扫描):
// 逆序扫描 // 时间复杂度 O(n),空间复杂度 O(1) class Solution { public: int lengthOfLastWord(string s) { int len = 0; int i = s.size() - 1; while (i >= 0) if (s[i] == ' ') --i; else break; while (i >= 0) if (s[i] != ' ') ++len, --i; else break; return len; } };
解题代码二(从前往后扫描):
// 顺序扫描,记录每个 word 的长度 // 时间复杂度 O(n),空间复杂度 O(1) class Solution { public: int lengthOfLastWord(const string& s) { int len = 0; for (int i = 0; i < s.size(); ) { if (s[i] != ' ') ++len, ++i; else { ++i; if (i < s.size() && s[i] != ' ') ++len; } } return len; } };
相关文章推荐
- [LeedCode OJ]#58 Length of Last Word
- Leetcode: Length of Last Word
- leetcode第一刷_Length of Last Word
- 【Leetcode】Length of Last Word
- Length of Last Word
- Length of Last Word
- leetcode--------------Length of Last Word
- Length of Last Word
- Leetcode Length of Last Word
- leetcode length of last word
- Length of Last Word
- leetcode58:Length of last word
- Length of Last Word
- LeetCode - Length of Last Word
- Length of Last Word --最后单词长度---如何优雅的写代码(重重)
- 【Leetcode】Length of Last Word
- [LeetCode]Length of Last Word@python
- LEETCODE-Length of Last Word
- Day5 Length of Last Word
- [Leetcode 3] 58 Length of Last Word