LeetCode热题(JS版)- 58. 最后一个单词的长度

84 阅读1分钟

题目

给定由单词和空格组成的字符串“s”,返回*字符串中最后一个单词的长度

word是仅由非空格字符组成的最大值子字符串。

示例 1:

输入: s = "Hello World"
输出: 5
解释:最后一个单词是长度为5的“World”。

示例 2:

输入: s = "   fly me   to   the moon  "
输出: 4
解释:最后一个单词是长度为4的“moon”。

示例 3:

输入: s = "luffy is still joyboy"
输出: 6
解释:最后一个单词是长度为6的“joyboy”。

思路

  • 倒着来,从有效的开头计数
function lengthOfLastWord(s: string): number {
    let trim = false;
    let index = 0;

    for(let i = s.length - 1; i >= 0; i--) {
        if(!trim) {
            if(s[i] === ' ') continue;
            trim = true;
        }
        if(s[i] === ' ') break;
        
        index ++;
    }

    return index
};

image.png