Length of Last Word

Tags: String, Easy

Question

Problem Statement

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 consists of non-space characters only.

For example,
Given s = "Hello World",
return 5.

题解

关键点在于确定最后一个字符串之前的空格,此外还需要考虑末尾空格这一特殊情况,容易想到的是利用一前一后两个索引记录,最后相减即可。但其实可以巧妙地直接利用非空字符串长度表示。除了通常简单粗暴的方法,我们还可以尝试使用正则表达式这一利器对字符串进行处理。

Python

  1. class Solution(object):
  2. def lengthOfLastWord(self, s):
  3. """
  4. :type s: str
  5. :rtype: int
  6. """
  7. if s is None: return 0
  8. last_word = s.split()
  9. return len(last_word[-1]) if last_word else 0

Python

  1. class Solution(object):
  2. def lengthOfLastWord(self, s):
  3. """
  4. :type s: str
  5. :rtype: int
  6. """
  7. if s is None: return 0
  8. m = re.search(r'(?P<word>\S+)\s*$', s)
  9. return len(m.group('word')) if m else 0

Python

  1. class Solution(object):
  2. def lengthOfLastWord(self, s):
  3. """
  4. :type s: str
  5. :rtype: int
  6. """
  7. if s is None: return 0
  8. cnt = 0
  9. for c in reversed(s):
  10. if c == ' ':
  11. if cnt > 0: break
  12. else:
  13. cnt += 1
  14. return cnt

C++

  1. class Solution {
  2. public:
  3. int lengthOfLastWord(string s) {
  4. if (s.empty()) return 0;
  5. int x = s.find_last_not_of(' ');
  6. return (x == std::string::npos) ? 0 : x - s.find_last_of(' ', x);
  7. }
  8. };

C++

  1. class Solution {
  2. public:
  3. int lengthOfLastWord(string s) {
  4. if (s.length() == 0) return 0;
  5. int cnt = 0;
  6. for (int i = s.length() - 1; i >= 0; --i) {
  7. if (s[i] == ' ') {
  8. if (cnt > 0) break;
  9. } else {
  10. cnt++;
  11. }
  12. }
  13. return cnt;
  14. }
  15. };

Java

  1. public class Solution {
  2. public int lengthOfLastWord(String s) {
  3. if (s == null || s.isEmpty()) return 0;
  4. int len = 0;
  5. for (int i = s.length() - 1; i >= 0; i--) {
  6. if (s.charAt(i) == ' ') {
  7. if (len > 0) return len;
  8. } else {
  9. len++;
  10. }
  11. }
  12. return len;
  13. }
  14. }

源码分析

注意检查输入参数和索引即可,当前长度信息和当前索引字符是否为空格这两种信息可以结合使用避免硬标记。

复杂度分析

遍历一次,时间复杂度 O(n),不复制源字符串,空间复杂度 O(1).