leetcode-58-length of last word

Problem Description:

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.

题目大意:

返回一个字符串中最后一个单词的长度。如果不存在,则返回0

Solutions:

先去掉尾部空格再计算最后一个单词长度即可。

Code in C++:

class Solution {
public:
    int lengthOfLastWord(string s) {
        if(s=="") return 0;
        int i = s.length()-1;
        int count = 0;
        while(i>=0){
            if(count==0&&s[i]==' ') i--;
            else if(s[i]!=' '){
                i--;count++;
            }else if(count>0&&s[i]==' ') break;

        }
        return count;
    }
};