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
.
#include<iostream>
using namespace std;
class Solution {
public:
int lengthOfLastWord(const char *s) {
if (s == NULL)
return 0;
int ans = 0, last= 0;
/* 当遇到字母时,ans++; 遇到空格之后的第一个字符时
*(注意:不是遇到空格后就直接置0,这样会出现错误(eg:s="adv fb ")),ans重新置零(ans = 0)
*/
while (*s != '\0')
{
if (*s == ' ')
{
ans = 0;
}
else
{
ans++;
}
if (ans > 0)
last = ans;
s++;
}
return last;
}
};
void main()
{
Solution solu;
char *s = "adf f kkk ";
int ans = solu.lengthOfLastWord(s);
cout << ans << endl;
}