且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

[LintCode] Length of Last Word 求末尾单词的长度

更新时间:2022-02-01 00:21:05

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 ,如需转载请自行联系原博主。