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.
解題報告:
用個變量last保存遍歷到當前位置的最後一個空格位置,只要當前字符不是空格,就更新
res,這樣下來,最終res裡面存放的就是所要求的結果.需要注意的是,last變量的初值.
class Solution {
public:
int lengthOfLastWord(const char *s)
{
if (s == NULL)
return 0;
int res = 0,last = -1;
for (int i = 0; s[i]; ++i)
{
if( s[i] == ' ')
{
last = i;
continue;
}
res = i - last;
}
return res;
}
};