Given a string s consists of upper/lower-case alphabets and empty space characters ' '
, return the length of last word in the string.
If the last word does not exist, return 0.
Note: A word is defined as a character sequence consists of non-space characters only.
For example,
Given s = "Hello World"
,
return 5
.
两个下标,head搜索非空格元素,last搜索head后的第一个空格或者字符串结尾。检测到单词后保存至lastlen里。
class Solution { public: int lengthOfLastWord(string s) { const unsigned int len = s.size(); unsigned int head,last,lastlen; head = ; last = ; lastlen = ; if (!len) ; ) { // search for the first non-space character while ((s[head] == ' ') && (head != len)) head ++; if (head == len) return lastlen; last = head;
while ((last != len) && (s[last] != ' ')) last ++; if (last == len) return last - head; else { lastlen = last - head; head = last; } } } };