Here is the HashMap based implementation of the function checking whether two strings are anagrams:
Example:
isAnagram("SAVE", "VASE") // returns true
isAnagram("SAV", "VASE") // returns false
isAnagram("SAVE", "VAS") // returns false
isAnagram("SAVE", "VAEE") // returns false
My implementation:
def isAnagram(value1: String, value2: String): Boolean = {
value1.length == value2.length && {
val index = new mutable.HashMap[Char, Int]()
def addToIndex(c: Char) = index(c) = index.getOrElse(c, 0) + 1
value1.foreach(c => addToIndex(c))
def decrementAndCheckInIndex(c: Char): Boolean = index.get(c) match {
case None => false
case Some(count) => index(c) = count - 1; true
}
value2.forall(decrementAndCheckInIndex) && index.forall { case (key, value) => value == 0 }
}
}
Could you please provide feedback on this code. I am interested in the mutable data structure use here, is it ok? And in general, what can I make better?