/*
 * 演算法 / Algorithm:
 *   與 C 解法相同：從尾端向前跳過空格，再向前計數最後一個單字長度。
 *   Same as the C solution: skip trailing spaces from the end, then count
 *   the length of the last word while walking left.
 */

#include <string>  // 使用 std::string / use std::string

class Solution {
public:
    // 參數用 const std::string& 傳參考，避免複製整個字串
    // Pass by const reference to avoid copying the whole string
    int lengthOfLastWord(const std::string& s) {
        // int 可放下 10^4，安全 / int can hold 10^4 safely
        // s.size() 回傳 size_t (無號)，所以先轉成 int 才能變負
        // s.size() returns size_t (unsigned); cast to int so it can go negative
        int i = static_cast<int>(s.size()) - 1;  // 從最後一個索引開始 / start at last index

        // 跳過結尾空格 / skip trailing spaces
        while (i >= 0 && s[i] == ' ') {
            --i;  // 前綴 -- 比後綴 -- 略有效率，效果相同 / pre-decrement, same effect
        }

        int length = 0;  // 計數器 / counter

        // 數出最後一個單字的長度 / count the length of the last word
        while (i >= 0 && s[i] != ' ') {
            ++length;  // 每碰到一個非空格就 +1 / +1 for each non-space char
            --i;       // 往左移 / move left
        }

        return length;  // 回傳結果 / return the answer
    }
};
