class Solution {
public:
int lengthOfLastWord(string s) {
//定义字符串长度
int index=s.size()-1;
//通过反向遍历,首先锁定最后一个字符,然后往前遍历
while(s[index]==' ')
{
index--;
}
//定义单词长度
int wordlongth=0;
//保证index大于0,并且反向遍历的字符不是空格
while(index >= 0&&s[index]!=' ')
{
wordlongth ++;
index--;
}
//返回单词长度
return wordlongth;
}
};
最后一个单词的长度
最新推荐文章于 2024-09-09 18:27:53 发布