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.
将string从后往前读,若最后一个为空格,继续向前读,直到读到第一个字母或读完,若没有读完再开始计数,直到读到空格
class Solution {
public:
int lengthOfLastWord(string s) {
int len=s.length();
if(len==0){
return 0;
}
else{
int n=0;
int i=len-1;
while(i>=0&&s[i]==' '){
i--;
}
while(i>=0&&s[i]!=' '){
i--;
n++;
}
return n;
}
}
};