第一個代碼可以正常作業并顯示正確的答案,即 19。
function findLongestWordLength(str) {
let high = 0;
let word = str.split(" ");
for(let i = 0; i < word.length; i )
{
if (word[i].length > high)
high = word[i].length;
}
console.log(high)
}
findLongestWordLength("What if we try a super-long word such as otorhinolaryngology");
下面的第二個代碼僅在“超長”一詞之前有效,并記錄10作為最終輸出,這是不正確的。我試圖弄清楚這里出了什么問題。它適用于其他句子,
以供參考
句子中str.length為60(包括空格),整個句子之間有9個空格
function findLongestWordLength(str) {
let high = 0;
let count = 0;
for (let i = 0; i < str.length; i ) {
if (str[i] != " ") {
count ;
} else {
if (count >= high)
high = count;
count = 0;
}
}
return high;
}
findLongestWordLength("What if we try a super-long word such as otorhinolaryngology");
uj5u.com熱心網友回復:
count可能在回圈結束時保持一個非零值,這將被忽略。只需在回圈末尾添加一個檢查即可更新該值。
for(let i = 0; i < str.length; i )
{
if (str[i] != " ") count ;
else
{
if(count >= high) high = count;
count = 0;
}
}
if(count >= high) high = count;
uj5u.com熱心網友回復:
為了得到 19,你必須用空格結束你的字串。因為最后一個字符"otorhinolaryngology"是 a 'y',所以您只需在最后增加 count 并且您永遠不會達到else將更新為高的條件。在最后放置一個空格,添加一個額外的條件檢查是否i == str.length -1或簡單地使用長度演算法,或者,如我所愿,使用這樣的減速器:
const findLongestWordLength = str => str.split(' ').reduce((acc, word) => word.length > acc ? word.length : acc, 0)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/447468.html
標籤:javascript 算法 功能
