0%

[Leetcode] 58. Length of Last Word (C++)

题目描述

题目链接:58. Length of Last Word

Given a string s consists of upper/lower-case alphabets and empty space characters ‘ ‘, return the length of last word (last word means the last appearing word if we loop from left to right) in the string.

If the last word does not exist, return 0.

Note: A word is defined as a maximal substring consisting of non-space characters only.

例子

例子 1

Input: “Hello World”
Output: 5

解题思路

通过两个 while 循环从后往前遍历,首先找到第一个不为空格的字符,然后在该点定位继续往前遍历直至遇到第一个空格为止。要注意边界条件不能越界,代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <string>

class Solution {
public:
int lengthOfLastWord(std::string s) {
int ptr = s.length() - 1;
int len = 0;

while (ptr >= 0 && s[ptr] == ' ') ptr--;
if (ptr < 0) return len;
while (ptr >= 0 && s[ptr--] != ' ') len++;

return len;
}
};
  • 时间复杂度: O(n)
  • 空间复杂度: O(1)