Recca Chao 的 gitHub page

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

View on GitHub

Kotlin Leetcode - 520. Detect Capital

題目連接

class Solution {
    fun detectCapitalUse(word: String): Boolean {

    }
}

解題思路

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

處理起來非常的直觀

根據題目的要求

要判斷下列幾個滿足條件

Kotlin 參考解答

class Solution {
    fun detectCapitalUse(word: String): Boolean {
        val numOfCapital = word.filter { it in 'A'..'Z' }.length
        val firstCapitalIndex = word.indexOfFirst { it in 'A'..'Z' }
        return numOfCapital == word.length 
                || numOfCapital == 0
                || (numOfCapital == 1 && firstCapitalIndex == 0)
    }
}

回到 leetcode 列表