algorighm/top-interview-leetcode150/numbers-and-strings/58最后一个单词的长度.js

43 lines
1.2 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* 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;
}