# 58 - Length of Last Word

解法一 - 取出 lastWord,算長度

一開始的直覺做法如下:

class Solution {
public:
    int lengthOfLastWord(string s) {
        size_t found = s.find_last_of(" ");

        //記得從 found+1開始,才不會包含到 space
        string lastWord = s.substr(found+1); 

        return lastWord.length();
    }
};

但是會掛在這個 case:

  1. "a " or "b a ": 我的輸出是 0,但應該要輸出 1。這是因為我的實作會被最後面的空白騙到。

一個繞開的方法就是先把最後面的空白都移除掉:

class Solution {
public:
    int lengthOfLastWord(string s) {
        if(s.empty()) return 0;

        while(s[s.length()-1] == ' ')
            s = s.substr(0, s.length()-1);

        size_t found = s.find_last_of(" ");
        string lastWord = s.substr(found+1);
        return lastWord.length();
    }
};

效率如下: Runtime: 0 ms, faster than 100.00% of C++ online submissions for Length of Last Word. Memory Usage: 9.5 MB, less than 5.00% of C++ online submissions for Length of Last Word.

解法二 - 從字串尾端開始往前找,找到第一個非 space 的 char 就開始數長度,直到數到 space

實作如下:

class Solution {
public:
    int lengthOfLastWord(string s) {
        int count = 0;

        for(int i=s.length()-1; i>=0; i--) {
            if(s[i] != ' ') count++;
            if(count != 0 && s[i] == ' ') break;
        }

        return count;
    }
};

效率差不多:

Runtime: 4 ms, faster than 85.62% of C++ online submissions for Length of Last Word. Memory Usage: 8.8 MB, less than 40.76% of C++ online submissions for Length of Last Word.

Last updated