Is there a way to check if two strings contain the same characters. For example,
abc, bca -> true
aaa, aaa -> true
aab, bba -> false
abc, def ->
Agree to what @Jean says above for an efficient solution using HashMap. This problem is also called Anagram. Below is the solution in Scala.
Note: cleanString is where whitespaces are removed and all characters are lowercase
def isAnagram(cleanString1, cleanString2) = {
createHashMap(cleanString1) == createHashMap(cleanString2)
}
def createHashMap(str: String): immutable.HashMap[Char, Int] = {
str.foldLeft(immutable.HashMap.empty[Char, Int]) { (acc, next)
=> if (acc.contains(next)) acc + (next -> (acc(next) + 1))
else acc + (next -> 1)
}
}