时间轴
字符串
题目:
直接查找两个点,第一个是最后一个单词的结束单词,第二个是最后一个单词开始的前一个。注意 start 要初始化为-1,是为了应对 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;
} };
|