code, programming, javascript-5113374.jpg

[LeetCode][javascript] 2114. Maximum Number of Words Found in Sentences Solution

分享

最近重新拾起 javascript 的練習,以新手的角度用LeetCode來練手,會用自己能夠理解的白話語言來解釋,有錯誤的話請多多包涵也不吝給予指教。

sentence is a list of words that are separated by a single space with no leading or trailing spaces.

You are given an array of strings sentences, where each sentences[i] represents a single sentence.

Return the maximum number of words that appear in a single sentence.

關鍵在於計算 space 空白,找出哪個句子擁有最長的句子,其實就是找到後 空白數量加一

Example 1:

this is great thanks very much => 5個空白,6個句子

Input: sentences = ["alice and bob love leetcode", "i think so too", "this is great thanks very much"]
Output: 6
Explanation: 
- The first sentence, "alice and bob love leetcode", has 5 words in total.
- The second sentence, "i think so too", has 4 words in total.
- The third sentence, "this is great thanks very much", has 6 words in total.
Thus, the maximum number of words in a single sentence comes from the third sentence, which has 6 words.

Example 2:

第二個跟第三個都是2個空白,3個句子

Input: sentences = ["please wait", "continue to fight", "continue to win"]
Output: 3
Explanation: It is possible that multiple sentences contain the same number of words. 
In this example, the second and third sentences (underlined) have the same number of words.

Constraints:

  • 1 <= sentences.length <= 100
  • 1 <= sentences[i].length <= 100
  • sentences[i] consists only of lowercase English letters and ' ' only.
  • sentences[i] does not have leading or trailing spaces.
  • All the words in sentences[i] are separated by a single space.

Solution:

首先來個只求過關的暴力解,直接用雙層迴圈做計算,第一層迴圈是有幾個句子,第二層迴圈是句子裡有幾個空白

    var space = ' '
    var max = []
    var count = 0
    
    for(var i=0;i<sentences.length;i++){
        for(var j=0;j<sentences[i].length;j++){
            if(sentences[i][j] === space){
                 count++
            }
        }
        max.push(count)
        count = 0
    }
    
    var result = Math.max(...max)

    return result + 1

Submissions:

Solution2:

試著用一層迴圈解決,運用 split技巧,分割完直接看長度是多少。

var result = [];
for(let i = 0; i < sentences.length;i++){
   result.push(sentences[i].split(" ").length);
}

return Math.max(...result);
分享
Scroll to Top