您的位置:首页 > 其它

[LeetCode] Length of Last Word

2015-06-28 16:11 337 查看
Well, the basic idea is very simple. Start from the tail of
s
and move backwards to find the first non-space character. Then from this character, move backwards and count the number of non-space characters until we pass over the head of
s
or meet a space character. The count will then be the length of the last word.

class Solution {
public:
int lengthOfLastWord(string s) {
int len = 0, tail = s.length() - 1;
while (tail >= 0 && s[tail] == ' ') tail--;
while (tail >= 0 && s[tail] != ' ') {
len++;
tail--;
}
return len;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: