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.
Seen this question in a real interview before?
Yes
最后一句话的长度
分析:
给定一个字符串s由大小写字母和空白符组成,返回最后一个单词的长度(如果最后一个词不存在,则返回0)
提示:一个单词背定义为仅有非空个字符组成的字符序列
这道题其实不难,唯一的小陷阱就是最后括号里面的提示,表明可能又很多的空格结尾,这样的话,我们只能返回0,所以,我们可以换个思路,从字符串尾部开始,排除空格,然后再到空格结束,这样,可以找出最后一个单词的长度。
class Solution {
public:
int lengthOfLastWord(string s) {
int len = s.length();
int count = 0;
while(s[len-1]==' ')
len--;
for(int i=len-1;i>=0;i--)
{
if(s[i]==' ')
break;
count++;
}
return count;
}
};
本文介绍了一种通过从字符串尾部开始遍历的方法来找出最后一个单词长度的技术。此方法适用于包含字母和空格的字符串,能够有效处理末尾多余空格的情况。
389

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



