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

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;
    }
};

本文转自博客园Grandyang的博客,原文链接:求末尾单词的长度[LintCode] Length of Last Word ,如需转载请自行联系原博主。

上一篇:Rails中Form标签JavaScript验证


下一篇:分析MySQL数据类型的长度