问题描述:
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.
分析:这道题很简单,只要从后向前,将空格过滤掉,然后如果没有了,直接返回0,然后再从后向前查找,当出现空格时,退出。返回计数。
代码如下:0ms
int lengthOfLastWord(char* s) {
int length = strlen(s);
int index = length-1;
while(index>=0&&s[index]==' ')
index--;
if(index<0)
return 0;
int count = 0;
while(index>=0&&s[index]!=' ')
{
count++;
index--;
}
return count;
}