首页 > ACM题库 > LeetCode > LeetCode-Length of Last Word[字符串]
2014
11-19

LeetCode-Length of Last Word[字符串]

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.

标签: String
分析

细节实现题。

代码1

// LeetCode, Length of Last Word
// 偷懒,用 STL
// 时间复杂度O(n),空间复杂度O(1)
class Solution {
public:
    int lengthOfLastWord(const char *s) {
        const string str(s);
        auto first = find_if(str.rbegin(), str.rend(), ::isalpha);
        auto last = find_if_not(first, str.rend(), ::isalpha);
        return distance(first, last);
    }
};

代码2

// LeetCode, Length of Last Word
// 顺序扫描,记录每个 word 的长度
// 时间复杂度O(n),空间复杂度O(1)
class Solution {
public:
    int lengthOfLastWord(const char *s) {
        int len = 0;
        while (*s) {
            if (*s++ != ' ')
                ++len;
            else if (*s && *s != ' ')
                len = 0;
        }
        return len;
    }
};