[LeetCode]Length of Last Word

Length of Last Word:

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 ”(a后面有个空格),否则不能accepted。

class Solution {
public:
    int lengthOfLastWord(string s) {
        int len = s.size(), re = 0;
        if(len==0) return 0;
        for(int i = len - 1; i >= 0; i--){
            if(s[i] != ' ') re++;
            else if(re!=0) break;
        }
        return re;
    }
};

posted @ 2017-12-17 00:00  liangf27  阅读(57)  评论(0编辑  收藏  举报