我需要编写一个返回 List
的函数的 (Char, Int)
对给定输入 String
.
我的解决方案产生了正确的结果,但我想知道是否有更好的方法:
def countChars(s: String): List[(Char, Int)] = {
s.groupBy(c => c.toLower).flatMap(e => List((e._1, e._2.length))).toList
}
这会在工作表中产生如下结果:
countChars("Green Grass")
// res0: List[(Char, Int)] = List(('e', 2), ('s', 2), ('n', 1), ('a', 1), (' ', 1), ('g', 2), ('r', 2))
最佳答案
制作一个单例列表只是为了扁平化它是多余的。
"Green Grass".groupBy(c => c.toLower).map(e => (e._1, e._2.length)).toList
关于scala - 字符串中唯一字符的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23847338/