找出字符串中的最长单词 返回给出的句子中,最长单词的长度。
函数的返回值应是一个数字。
Solution 1
function findLongestWordLength(str) {
let longestLength = 0;
let currentLength = 0;
for (let i = 0; i < str.length; i++) {
if (str[i] === " ") {
if (currentLength > longestLength) {
longestLength = currentLength;
}
currentLength = 0;
} else {
currentLength++;
}
}
if (currentLength > longestLength) {
longestLength = currentLength;
}
/*第一个if中没有进行最后一轮当前与最大单词之间的比较,
这就意味着如果单词最后一个是最大单词的话,返回的最大单词并不是最大单词,
所以这里currentLength和longestLength要整体再比较一次*/
return longestLength;
}
Solution 2
function findLongestWordLength(str) {
let words = str.split(' ');
let maxLength = 0;
for (let i = 0; i < words.length; i++) {
if (words[i].length > maxLength) {
maxLength = words[i].length;
}
}
return maxLength;
}
/*获取字符串并将其转换为单词数组。声明一个变量以跟踪从 0 到单词数组长度的最大长度和循环。
然后通过将当前单词与前一个单词进行比较并存储新的最长单词来检查最长单词。
在循环结束时,只需返回变量 maxLength 的数字值。*/
Solution 3
function findLongestWordLength(s) {
return s
.split(' ')
.reduce((longest, word) => Math.max(longest, word.length), 0);
}
/*使用 .reduce()*/
Solution 4
function findLongestWordLength(str) {
return Math.max(...str.split(" ").map(word => word.length));
}
/*使用 .map()*/
Solution 5
function findLongestWordLength(str) {
// split the string into individual words
const words = str.split(" ");
// words only has 1 element left that is the longest element
if (words.length == 1) {
return words[0].length;
}
// if words has multiple elements, remove the first element
// and recursively call the function
return Math.max(
words[0].length,
findLongestWordLength(words.slice(1).join(" "))
);
}
findLongestWordLength("The quick brown fox jumped over the lazy dog");
/*第一行将字符串拆分为单个单词。然后我们检查单词是否只剩下 1 个元素。
如果是这样,那么这是最长的元素,我们返回它。
否则,我们删除第一个元素并递归调用函数 findLongestWord,
返回第一个结果长度和递归调用之间的最大值。*/