思路:从最后一个字符开始遍历,先用一个while跳过最后面所有的空格,再遍历非空格字符并计数,遇空格则停止;
int lengthOfLastWord(string s)
{
int len = s.length();
if (len == 0)
return 0;
int count = 0;
int i = len - 1;
while (i >= 0 && s[i] == ' ')//skip all last space;
{
--i;
}
while (i >= 0 && s[i] != ' ')//traverse and count the character which is not space;
{
count++;
--i;
}
return count;
}