题目:
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
.
先算出字符串的总长度,从最后一个字符元素开始往前推。
字母字前的空格忽略,从第一个出现的字母开始,计算长度。
class Solution {
public:
int lengthOfLastWord(const char *s) {
int i=strlen(s)-1,num=0;
while(s[i]==' ')--i;
while(i>=0&& ((s[i]<='z'&&s[i]>='a')||(s[i]<='Z'&&s[i]>='A')) )
{
i--;
num++;
}
return num;
}
};