题目描述
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",
return5.
思路:先求出字符串长度,再从右往左遍历字符串;遍历时,先跳过最右侧的空格,然后才开始计算最后一个单词的长度。
代码:
class Solution {
public:
int lengthOfLastWord(const char *s) {
if(s == NULL)
return 0;
int num=0;
while(s[num] != '\0'){//计算字符串长度
++num;
}
if(num == 0)//如果字符串是空的,即s="",返回0。
return 0;
else{
int i = num-1;
while(i>=0 && s[i] == ' ')//s="a "时,跳过字符串末尾的空格。
--i;
int len=0;
while(i>=0 && s[i] != ' '){//开始遍历最后一个单词的长度
++len;
--i;
}
return len;
}
}
};