Cover image for 面试经典150题 P58 最后一个单词的长度

面试经典150题 P58 最后一个单词的长度


时间轴

时间轴

2025-10-12

init

字符串

题目:

直接查找两个点,第一个是最后一个单词的结束单词,第二个是最后一个单词开始的前一个。注意 start 要初始化为-1,是为了应对 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;  }};
评论加载中…