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.
1:从头遍历字符串,并记下最后一个非空字符的位置,2:如果全是空格字符,直接返回0; 3:从最后一个非空格字符向前遍历,获得最后一个单词的长度
int lengthOfLastWord(const char *s) {
if(s == NULL || *s == '\0')
return 0;
int index = -1;
int count = 0;
for(int i = 0; s[i] != '\0'; i++)
{
if(s[i] == ' ')
{
continue;
}
else
{
index = i;
}
}
if(index == -1)
return 0;
for(int i = index; i >= 0; i--)
{
if(s[i] != ' ')
{
count++;
}
else
{
break;
}
}
return count;
}