给你一个字符串 s,由若干单词组成,单词前后用一些空格字符隔开。返回字符串中 最后一个 单词的长度。

单词 是指仅由字母组成、不包含任何空格字符的最大子字符串。

一般思路

function lengthOfLastWord(s: string): number {
    // 1. trim() 去除前后空白字符(包括 \u0020 和 \u00A0 等)
    const trimmed = s.trim();
    // 2. 找到最后一个普通空格的位置
    const lastIndex = trimmed.lastIndexOf(" ");
    // 3. 长度等于总长减去最后一个空格的索引再减 1
    return trimmed.length - 1 - lastIndex;
};

反向遍历

function lengthOfLastWord(s: string): number {
    let end = s.length -1 
    while(end>=0 && s[end] === " "){
	    end --
    }
    let start = end 
    
    while(start>=0 && s[start] !== " "){
	    start--
    }
    return end - start
};