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
.
考虑World会出现的情况有以下几种情况:
“World”
"World "
"World "
" "
思路为:
从后面倒着开始统计,如果当前已经开始统计,则遇到空格后停止,并输出长度。
class Solution {
public:
int lengthOfLastWord(string s) {
int len = 0,int lenS = s.length();
bool flag = false;
while( lenS >= 1){
if (s[lenS - 1] == ' '&& true == flag)
return len;
if (s[lenS - 1] != ' '){
flag = true;
++len;
}
--lenS;
}
return len;
}
};
这里显性的给出了是否已经刚开始统计的标志FLAG, 其实如果考虑len的值,当len的值为0时,即没有开始统计,可以优化为:
class Solution {
public:
int lengthOfLastWord(string s) {
int len = 0;
int lenS = s.length();
while( lenS >= 1)
{
if (s[lenS - 1] == ' '&& len != 0)
{
return len;
}
if (s[lenS - 1] != ' ')
{
++len;
}
--lenS;
}
return len;
}
};