/*
 * 演算法 / Algorithm:
 *   1. 從字串尾端往前掃，先跳過所有結尾的空格。
 *      Scan from the end, skipping all trailing spaces first.
 *   2. 接著一邊往前走一邊計數，直到碰到空格或走到字串開頭。
 *      Then count non-space chars walking left until a space or start of string.
 */

#include <string.h>  // 引入 strlen / include strlen

int lengthOfLastWord(char* s) {
    // strlen 回傳 '\0' 之前的字元數；型別是 size_t (無號)
    // strlen returns the number of chars before '\0'; its type is size_t (unsigned)
    int i = (int)strlen(s) - 1;  // i 指向最後一個字元 / i points to the last character

    // 第一個迴圈：跳過末尾的空格
    // First loop: skip trailing spaces
    // 條件 i >= 0 防止走出字串左邊界 / i >= 0 guards against falling off the left end
    while (i >= 0 && s[i] == ' ') {
        i--;  // 往左移一格 / move one step left
    }

    int length = 0;  // 累計最後一個單字的長度 / counter for the last word's length

    // 第二個迴圈：從最後一個字元往前數，直到再次遇到空格
    // Second loop: count characters going left until we meet another space
    while (i >= 0 && s[i] != ' ') {
        length++;  // 又數到一個非空格字元 / found one more non-space character
        i--;       // 繼續往左 / keep moving left
    }

    return length;  // 回傳答案 / return the result
}
