指针 + 反向遍历
- 思路:
- 用一个指针反向遍历字符串;
- 用一个变量计数统计长度;
class Solution {
public:
int lengthOfLastWord(string s) {
int index = s.size() - 1;
while (s[index] == ' ') {
index--;
}
int length = 0;
while (index >= 0 && s[index] != ' ') {
length++;
index--;
}
return length;
}
};