Recca Chao 的 gitHub page

推廣網站開發,包含 Laravel 和 Kotlin 後端撰寫、自動化測試、讀書心得等。Taiwan Kotlin User Group 管理員。

View on GitHub

Kotlin Leetcode - 2114. Maximum Number of Words Found in Sentences

題目連接

class Solution {
    fun mostWordsFound(sentences: Array<String>): Int {
        
    }
}

解題思路

這一題考的是對字串的處理

基本上有兩種思路方向

第一個是計算有幾個空白之後加一

第二個是利用 split 拆分後計算個數

Kotlin 參考解答

點擊展開解答

我們可以用雙重迴圈來計算空白數

class Solution {
    fun mostWordsFound(sentences: Array<String>): Int {
        var max = 0
        sentences.forEach {
            var k = 0
            it.forEach { if (it == ' ') k++ }
            if (k > max) max = k
        }
        return max + 1
    }
}

如果用拆分的方式

可以寫成單個表達式

class Solution {
    fun mostWordsFound(sentences: Array<String>) =
        sentences.maxOfOrNull {
            it.split(" ").size
        } ?: 0
}

回到 leetcode 列表