1、问题概述:给一个字符串,中间掺杂空格,要求字符串中 最后一个 单词的长度
2、示例
示例 1:
输入:s = "Hello World"
输出:5
解释:最后一个单词是“World”,长度为 5。
示例 2:
输入:s = " fly me to the moon "
输出:4
解释:最后一个单词是“moon”,长度为 4。
示例 3:
输入:s = "luffy is still joyboy"
输出:6
解释:最后一个单词是长度为 6 的“joyboy”。
3、分析
(1)从后面进行遍历
(2)遍历退出条件:当遇到 空格 && count>0 跳出本次循环
4、代码
int lengthOfLastWord(char* s) {
int count=0;
// 判断是否有字符串
if(strlen(s)==0) return -1;
// 逆向思维,从后往前找
for(int i=strlen(s)-1;i>=0;i--){
if(s[i]!=' '){
count++;
}
if(s[i]==' ' && count>0){
break;
}
}
return count;
}