#include <iostream>
#include <string>
using namespace std;
class Solution {
public:
int lengthOfLastWord(string s) {
int index = s.size() - 1;
while (s[index] == ' ') {
index--;
}
int wordLength = 0;
while (index >= 0 && s[index] != ' ') {
wordLength++;
index--;
}
return wordLength;
}
};
int main() {
Solution sol;
string input = "Hello World";
int result = sol.lengthOfLastWord(input);
cout << "Length of the last word: " << result << endl;
return 0;
}
思路:既然是求取最后一个单词的长度,本来是从左向右搜索,那我从右向左搜索,首先求出长度,如果检测到字符串为空进行判断,直至当前字符串不为空格求出索引,然后再向左去判断,如果出现空格和当前长度为0了,则返回长度。