从后向前寻找,跳过尾部的空格。
也可用STL中,find_last_not_of()与rfind()完成对第一个非空格字符与字符后第一个空格的寻找。
时间复杂度:O(N)
C++代码:
class Solution {
public:
int lengthOfLastWord(string s) {
if (s.empty())
return 0;
auto it = s.rbegin();
int count = 0;
while (*it == ' ' && it != s.rend())
{
count++;
it++;
}
if (count == s.length())
return 0;
while (it != s.rend() && *it != ' ')
it++;
return it - s.rbegin() - count;
}
};