Created
February 16, 2020 20:04
-
-
Save msiddiqi/8ea6dc21ba062ee9fd4ce452c2a8dcad to your computer and use it in GitHub Desktop.
checking if two strings are anagrams
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def areAnagrams(first: String, second: String) = { | |
(first, second) match { | |
case x if first.length != second.length => false | |
case _ => { | |
val firstGroup = first.groupBy(i => i).map { case (item, repetitions) => (item, repetitions.size) } | |
val secondGroup = second.groupBy(i => i).map { case (item, repetitions) => (item, repetitions.size) } | |
firstGroup.size == secondGroup.size && | |
firstGroup.forall(item => item._2 == secondGroup.getOrElse(item._1, 0)) | |
} | |
} | |
} | |
println(areAnagrams("FRIED", "FIRED")) // TRUE | |
println(areAnagrams("SPEECH", "SPIECH")) // FALSE |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment