Cover image for Interview Classic 150 Questions P58 Length of Last Word

Interview Classic 150 Questions P58 Length of Last Word


Timeline

timeline

2025-10-12

init

string

Problem:

Directly find two positions: the first is the end of the last word, the second is the position before the start of the last word. Note that start should be initialized to -1 to handle the case s = ‘a’.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <string>
using std::string;

class Solution {
public:
int lengthOfLastWord(string s) {
int len = s.size();
int i = len - 1;
int end = 0, start = -1;

while (i >= 0) {
if (std::isalpha(s[i])) {
end = i;
break;
}
i--;
}

while (i >= 0) {
if (!std::isalpha(s[i])) {
start = i;
break;
}
i--;
}

return end - start;

}
};