[LeetCode] 58_最后一个单词的长度
题目要求
给定一个仅包含大小写字母和空格 ’ ’ 的字符串,返回其最后一个单词的长度。 如果不存在最后一个单词,请返回 0 。 说明:一个单词是指由字母组成,但不包含任何空格的字符串。 示例: 输入: “Hello World” 输出: 5
题目分析
记录空格数和最后一个字符的位置最后一个字符后面的所有空格从空格数中去掉遍历字符串,当剩余空格数为0时,最后一个字符的位置-前面字符的数目等于最后一个单词长度
注意点
可能会出现最后有很多连续空格的情况,这些属于废字符,要去掉。
代码
class Solution {
public:
int
lengthOfLastWord(string s
) {
int num_of_space
=0;
int last_word
=0;
int ans
=0;
for(int i
=0;i
<s
.length();++i
){
if(s
[i
]==' ')++num_of_space
;
else last_word
=i
;
}
num_of_space
-=(s
.length()-1-last_word
);
for(int i
=0;i
<s
.length();++i
){
if(num_of_space
==0){
ans
=last_word
-i
+1;
break;
}
if(s
[i
]==' ')--num_of_space
;
}
return ans
;
}
};