/** * https://leetcode.cn/problems/length-of-last-word/?envType=study-plan-v2&envId=top-interview-150 * @param {string} s * @return {number} */ const lengthOfLastWord = function (s) { return f1(s); }; /* 使用trim对字符做前后空格处理,之后使用split(" ")分割,最后返回split(" ")[s.length = 1].length */ function f1(s) { // 去除首尾空格,并按空格分割字符串 const words = s.trim().split(' '); // 返回最后一个单词的长度 return words[words.length - 1].length; } /* 方法2,从后往前遍历,按照题目的要求所给的测试用例至少会包含一个单词,直接从和往前遍历,先去除末尾空格,如果是空格就跳过 直到遇到不是空格的情况,之后再遍历这个末尾单词,如果不是空格就在统计的长度上加1,直到遇到这个单词前面的空格,结束循环,表示 单词统计完成 */ function f2(s) { let len = 0; // 统计末尾单词长度 let i = s.length - 1; // 有效字符的位置 // 去除末尾空格 while (i >= 0 && s[i] === ' ') { i--; } // 统计末尾字符长度 while (i >= 0 && s[i] !== ' ') { len++; i--; } return len; }