给定一个字符串,查找其中的第一个重复字符。示例:
firstUnique("Vikrant")→NonefirstUnique("VikrantVikrant")→Some(V)Scala实现:
object FirstUniqueChar extends App {
def firstUnique(s: String): Option[Char] = {
val countMap = (s groupBy (c=>c)) mapValues(_.length)
def checkOccurence(s1: String ): Option[Char] = {
if (countMap(s1.head) > 1) Some(s1.head)
else if (s1.length == 1) None
else checkOccurence(s1.tail)
}
checkOccurence(s)
}
println(firstUnique("abcdebC"))
println(firstUnique("abcdef"))
}我也有一个跟进问题。如果我不想用递归来解决这个问题,那么推荐的方法是什么?当我发现第一个元素的计数超过1时,我可以不使用checkOccurence方法遍历字符串和break,但这需要中断,这在Scala中是不鼓励的。
发布于 2019-01-09 21:04:33
您的checkOccurrence(s)只是编写D0的一种笨拙的方式
您可以利用.distinct大大简化解决方案。
def firstUnique(s: String): Option[Char] =
s.zipAll(s.distinct, '\u0000', '\u0000')
.collectFirst({ case ab if ab._1 != ab._2 => ab._1 })https://codereview.stackexchange.com/questions/211151
复制相似问题