Recca Chao 的 gitHub page

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

View on GitHub

Kotlin Leetcode - 657. Robot Return to Origin

題目連接

class Solution {
    fun judgeCircle(moves: String): Boolean {
    }
}

解題思路

這一題考的是對字母的基本處理

只要 UD 的個數相等

並且 RL 的個數相等即可

Kotlin 參考解答

點擊展開解答

單個表達式解法如下

class Solution {
    fun judgeCircle(moves: String) = 
        moves.count{it == 'U'} == moves.count{it == 'D'}
        && moves.count{it == 'R'}  == moves.count{it == 'L'}
}

這個解法會重複對字串跑 4 次迴圈

如果希望只跑一次迴圈

我們可以換個方式撰寫

class Solution {
    fun judgeCircle(moves: String): Boolean {
        var x = 0
        var y = 0
        moves.forEach {
            when (it) {
                'U' -> y++
                'D' -> y--
                'R' -> x++
                'L' -> x--
            }
        }
        return x == 0 && y == 0
    }
}

回到 leetcode 列表