L58: 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.

For example,
Given s = “Hello World”,
return 5.

解题思路:遇到非’ ‘字符,用一个符号表示word開始,遇到’ ‘表示word结束,注意边界情况处理
优化:能够从字符串末尾開始处理

class Solution {
public:
    int lengthOfLastWord(string s) {
        int strLen = s.length();
        if(strLen == 0)
            return 0;

        int begin = 0;
        int end = 0;
        int pos = 0;
        bool word_start = false;
        while(pos < strLen)
        {
            if(s[pos] != ' ' && !word_start) 
            {
                begin = pos;
                word_start = true;
            }
            else if(s[pos] == ' ' && word_start)
            {
                end = pos;
                word_start = false;
            }
            pos++;
        }
        if (word_start && pos == strLen)
            end = strLen;
        return end - begin;
    }
};