gpt4 book ai didi

JavaScript:查找字符串中最大的单词

转载 作者:行者123 更新时间:2023-11-28 12:22:31 24 4
gpt4 key购买 nike

这是我的片段。我觉得这段代码满足算法,但没有通过。可能的原因是什么?

function findLongestWord(str, separator) {
var splitString = str.split(separator);
for (var i = 1; i <= splitString.length; i++) {
for (j = 1; j < splitString[i].length; j++) {
while (j === ' ') {
return j;
}
}
}
var greater;
if (j > greater) {
greater = j;
}
return greater;
}

findLongestWord("The quick brown fox jumped over the lazy dog", ' ');

最佳答案

这是您的代码,附有说明和一些使其正常工作的更改

function findLongestWord(str, separator) {
var splitString = str.split(separator);

// Define it as empty string
var greater = '';

// Start looping from 0th index upto the length
for (var i = 0; i < splitString.length; i++) {
for (j = 0; j < splitString[i].length; j++) {
// Don't know what this is
// `j` is the index, i.e. number, it cannot be equal to ` `
// I guess this is confused with the separator

// This can be removed without any problem
while (j === ' ') {
return j;
}
// No use code
}
// Here `j` is the length of the word
// Compare it with the length of greater word
if (j > greater.length) {
// Update the greater to current `i` string
greater = splitString[i];
}
}

// Return greater string.
return greater;
}

var longestWord = findLongestWord("The quick brown fox jumped over the lazy dog", ' ');
document.body.innerHTML = 'Longest Word: ' + longestWord;

<小时/>

经过很少优化的相同代码可以重写为

function findLongestWord(str, separator) {
var splitString = str.split(separator);
// Define it as empty string
var greater = '';

for (var i = 0, len = splitString.length; i < len; i++) {
if (splitString[i].length > greater.length) {
// Update the greater to current `i` string
greater = splitString[i];
}
}

return greater;
}

var longestWord = findLongestWord("The quick brown fox jumped over the lazy dog", ' ');
document.body.innerHTML = 'Longest Word: ' + longestWord;
console.log(longestWord);

我使用 ES6 的解决方案

您可以使用Array#reduceArrow functions 。对于 ES5 中的相同代码,请检查 this answer通过 @gurvinder372

str.split(' ').reduce((x, y) => x.length > y.length ? x : y);

function findLongestWord(str, separator) {
return str.split(' ').reduce((x, y) => x.length > y.length ? x : y);
}

var longestWord = findLongestWord("The quick brown fox jumped over the lazy dog", ' ');
document.body.innerHTML = 'Longest Word: ' + longestWord;
console.log(longestWord);

关于JavaScript:查找字符串中最大的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34892402/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com