[LintCode] 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.

Notice

A word is defined as a character sequence consists of non-space characters only.

 
Example

Given s = "Hello World", return 5.

 

LeetCode上的原题,请参见我之前的博客Length of Last Word

 

解法一:

class Solution {
public:
    /**
     * @param s A string
     * @return the length of last word
     */
    int lengthOfLastWord(string& s) {
        if (s.empty()) return 0;
        int res = 0;
        if (s[0] != ' ') res = 1;
        for (int i = 1; i < s.size(); ++i) {
            if (s[i] != ' ') {
                if (s[i - 1] == ' ') res = 1;
                else ++res;
            }
        }
        return res;
    }
};


解法二:

class Solution {
public:
    /**
     * @param s A string
     * @return the length of last word
     */
    int lengthOfLastWord(string& s) {
        int tail = s.size() - 1, res = 0;
        while (tail >= 0 && s[tail] == ' ') --tail;
        while (tail >= 0 && s[tail] != ' ' ) {
            --tail;
            ++res;
        }
        return res;
    }
};

 

posted @ 2016-07-27 23:35  Grandyang  阅读(487)  评论(0编辑  收藏  举报
Fork me on GitHub