Given a string, find the first repeating character in it.
Examples:
firstUnique("Vikrant")
→None
firstUnique("VikrantVikrant")
→Some(V)
Scala implementation:
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"))
}
I also have a followup question. What is the recommended way if I do not want to solve this problem with recursion? Instead of using the checkOccurence
method I can traverse through the string and break
when I find the first element with a count more than 1. But that will require a break, which is discouraged in Scala.