LeetCode之Determine if String Halves Are Alike(Kotlin)

问题:



方法:
很简单的问题,先把字符拆分,然后遍历统计命中的字符,最后比较数量即可。

class DetermineIfStringHalvesAreAlike {
    private val characters = listOf('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U')
    fun halvesAreAlike(s: String): Boolean {
        val halfOne = s.substring(0, s.lastIndex / 2 + 1)
        val halfTwo = s.substring(s.lastIndex / 2 + 1, s.lastIndex + 1)
        var sumOne = 0
        var sumTwo = 0
        for (ch in halfOne) {
            if (characters.contains(ch)) {
                sumOne++
            }
        }
        for (ch in halfTwo) {
            if (characters.contains(ch)) {
                sumTwo++
            }
        }
        return sumOne == sumTwo
    }
}

有问题随时沟通

具体代码实现可以参考Github

你可能感兴趣的:(LeetCode之Determine if String Halves Are Alike(Kotlin))