问题概述
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.
Example:
Input: "Hello World"
Output: 5
分析
这道题主要是考虑最后是不是空格,方法是倒着找不是空格的字符并计数,如果遇到空格且计数不是0,说明最后一个单词已经被计数了,所以可以返回了。
c++代码
class Solution {
public:
int lengthOfLastWord(string s) {
if(s.length()==0){
return 0;
}
int num = 0;
int l = s.length();
for(int i = l-1; i >= 0; i--){
if(s[i] != ' '){
num++;
}
if(s[i] == ' ' && num != 0) break;
}
return num;
}
};