题目描述
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) {
int count = 0;
int len = strlen(s);
//反向查找,末尾空格忽略,行中出现空格就终止循环
for(int i = len-1; i >= 0 ; i--){
if(s[i] == ' '){
if(count)
break;
}
else{
count++;
}
}
return count;
}
};
本文介绍了一种通过遍历字符串并忽略尾部空格来计算最后一个单词长度的方法。该方法适用于包含大小写字母及空格的字符串,对于不包含单词的情况能够返回0。
689

被折叠的 条评论
为什么被折叠?



