LeetCode Length of Last Word

58. Length of Last Word

Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word (last word means the last appearing word if we loop from left to right) in the string.

If the last word does not exist, return 0.

Note: A word is defined as a maximal substring consisting of non-space characters only.

Example:

Input: "Hello World"
Output: 5

本题要求一个字符串中最后一个单词的长度,比如”Hello World”,则返回5。需要注意结尾包含空格的情况,比如”Hello World “,还是要返回5。所以需要先删除尾部空格,然后再从后往前查找第一个空格,返回空格到结尾的长度。 完整代码如下:

class Solution {
public:
    int lengthOfLastWord(string s)
    {
        int e = s.size() – 1;
        while (e >= 0 && s[e] == ‘ ‘) {
            e–;
        }
        if (e < s.size() – 1) {
            s = s.substr(0, e + 1);
        }
        size_t tPos = s.find_last_of(‘ ‘);
        if (tPos == string::npos)
            return s.size();
        return s.size() – tPos – 1;
    }
};

本代码提交AC,用时4MS。

二刷。上述代码也过于复杂,还有字符串的substr,下面是更简洁的版本:

class Solution {
public:
    int lengthOfLastWord(string s)
    {
        int i = s.size() – 1;
        while (i >= 0 && s[i] == ‘ ‘)
            –i;
        if (i < 0)
            return 0;
        int j = i – 1;
        while (j >= 0 && s[j] != ‘ ‘)
            –j;
        return i – j;
    }
};

本代码提交AC,用时3MS。

Leave a Reply

Your email address will not be published. Required fields are marked *