15-最后一个单词的长度
给你一个字符串 s
,由若干单词组成,单词前后用一些空格字符隔开。返回字符串中 最后一个 单词的长度。
单词 是指仅由字母组成、不包含任何空格字符的最大子字符串。
方法一:使用字符串分割
可以使用字符串的 split
方法将字符串按空格分割成单词数组,然后取数组中的最后一个单词,计算其长度。
function lengthOfLastWord(s: string): number {
// 使用 split 方法按空格分割字符串
const words = s.trim().split(/\s+/);
// 如果分割后的数组不为空,返回最后一个单词的长度
if (words.length > 0) {
return words[words.length - 1].length;
}
return 0;
}
// 示例调用
const s = "Hello World";
const length = lengthOfLastWord(s);
console.log("最后一个单词的长度是:", length);
复杂度分析
- 时间复杂度:O(n),其中 n 是字符串的长度。
trim
方法和split
方法都需要遍历字符串。 - 空间复杂度:O(m),其中 m 是分割后单词的数量。
方法二:反向遍历
从字符串的末尾开始反向遍历,跳过末尾的空格,然后计算最后一个单词的长度。
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;
}
// 示例调用
const s2 = " fly me to the moon ";
const length2 = lengthOfLastWord(s2);
console.log("最后一个单词的长度是:", length2);
复杂度分析
- 时间复杂度:O(n),最坏情况下需要遍历整个字符串。
- 空间复杂度:O(1),只使用了常数级的额外空间。
方法三:使用正则表达式匹配
使用正则表达式匹配最后一个单词,然后计算其长度。
function lengthOfLastWord(s: string): number {
const match = s.match(/\w+(\s+|$)/g);
if (match) {
const lastWord = match[match.length - 1].trim();
return lastWord.length;
}
return 0;
}
// 示例调用
const s3 = "luffy is still joyboy";
const length3 = lengthOfLastWord(s3);
console.log("最后一个单词的长度是:", length3);
复杂度分析
- 时间复杂度:O(n),正则表达式匹配需要遍历字符串。
- 空间复杂度:O(m),其中 m 是匹配到的单词数量。
综上所述,方法二(反向遍历)在空间复杂度上表现最优,且代码相对简洁,是比较推荐的实现方式。