簡體   English   中英

查找字符串中最長的單詞

[英]Find the longest word in string

我正在嘗試解決這個任務 - “給定一個字符串,返回得分最高的單詞。得分可以通過以下方式計算:

  • 對於每個元音,在分數上加 1 (["a", "e", "i", "o", "u", "y"])
  • 對於每個常量 ["b", "d"] 從分數中減去 1

例如,“蝴蝶”的得分為 2,我們為每個元音(“u”、“e”、“y”)加 3,為常數(“b”)減 1。 單詞“day”的得分為 2(我們為“a”、“y”加 2)。 function 需要返回得分最高的單詞。

到目前為止,這是我的代碼:

function countVowels(string) {
  let vowels = ["a", "e", "i", "o", "u"] 
  let constants = ["b", "d"]

  let words = string.trim().split(" ")

  let highestScore = " ";
  let count =0;
  
  for(const c of words){
    for (let i=0; i<c.length; i++){

        if(vowels.includes(c[i])) {
        highestScore = c
        count++;
        }
        else if (constants.includes(c[i])) count--    
    }
}
console.log(highestScore)
return highestScore;

}

countVowels("what a beautiful day")

問題是我的代碼返回句子中的最后一個詞,而不是得分最高的詞。 如果我通過“多么美好的一天”,function 返回“一天”而不是“美麗”。 我似乎找不到返回正確值的方法。 任何建議和幫助表示贊賞。

您需要另一個變量來跟蹤您正在迭代的一個單詞的分數,與目前找到的最高分數分開。 更精確的變量名稱也會有所幫助 - highestScore聽起來像一個數字(分數),但您當前的代碼將它作為一個字符串。 考慮使用類似bestWordFoundSoFar的東西。

 function countVowels(string) { const vowels = ["a", "e", "i", "o", "u"] const constants = ["b", "d"] const words = string.trim().split(" ") let bestWordSoFar; let scoreOfBestWordSoFar = 0;; for (const word of words) { let thisWordScore = 0; for (const char of word) { if (vowels.includes(char)) thisWordScore++; else if (constants.includes(char)) thisWordScore-- } if (thisWordScore > scoreOfBestWordSoFar) { bestWordSoFar = word; scoreOfBestWordSoFar = thisWordScore } } return bestWordSoFar; } console.log(countVowels("what a beautiful day"));

.reduce可以使用一種更實用的方法來跟蹤並返回找到的最佳單詞。

 function countVowels(string) { const vowels = ["a", "e", "i", "o", "u"]; const constants = ["b", "d"]; const getWordScore = (word) => { let thisWordScore = 0; for (const char of word) { if (vowels.includes(char)) thisWordScore++; else if (constants.includes(char)) thisWordScore-- } return thisWordScore; }; return string.trim().split(" ").reduce((bestWordSoFar, word) => getWordScore(word) > getWordScore(bestWordSoFar)? word: bestWordSoFar); } console.log(countVowels("what a beautiful day"));

您不會重置分數 ( count ) 以將其個性化為每個單詞。 您可以使用Array#map來執行此操作,如下所示:

 function countVowels(string) { let vowels = ["a", "e", "i", "o", "u"] let constants = ["b", "d"] let words = string.trim().split(" ") const scores = words.map(word => { let score = 0; for (let i=0; i < word.length; i++){ if(vowels.includes(word[i])) { score++ } else if (constants.includes(word[i])) score-- } console.log( word, score ); //output each word and score return [word, score]; }).sort((a,b) => b[1] - a[1]); //sort the array in descending order of score return scores[0][0]; //return the WORD with highest score } console.log('Word with highest score: ' + countVowels("what a beautiful day") );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM