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

Classic Interview 150 Questions P58 Length of Last Word


Timeline

Timeline

2025-10-12

init

string

Problem:

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

123456789101112131415161718192021222324252627282930
#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;  }};
Loading comments…