题目:
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
描述:
给出一个小写字母组成的字符串,求最后一个单词的长度
分析:
需要设置一个标识符来表示最后一个单词是否已经开始,
如果单词已经开始,但是又遇到了空白,那么这个单词便结束了
样例:
"a ab abc "
" "
"a a "
"a c"
"Hello World"
代码:时间复杂度 O (n)
class Solution {
public:
int lengthOfLastWord(string s) {
int len = s.size(), result = 0, start = false;
for (int i = len - 1; i >= 0 ; -- i) {
if (s[i] != ' ') {
start = true;
++ result;
} else {
if (start) {
break;
}
}
}
return result;
}
};