題目
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.
分析
給出一個字符串饱苟,返回最后一個單詞的長度。依次計算單詞的長度藻茂,需要注意需要保存上個單詞的長度呀邢,防止出現(xiàn)的一連串的空格導致結果的丟失壁晒。
/*
測試數(shù)據(jù):
" ff "
" "
"Hello World"
*/
int lengthOfLastWord(char* s) {
int ans=0,lastans=0,length=0;
while(s[length]!='\0')
{
if(s[length]==' ')
{
if(ans!=0)lastans=ans;
ans=0;
}
else
ans++;
length++;
}
if(ans!=0)
return ans;
else
return lastans;
}