From 081f896d3162f9503d0b1529ff0ade2ca43f9163 Mon Sep 17 00:00:00 2001 From: Manmohan Krishna Date: Tue, 4 Apr 2023 01:52:29 +0530 Subject: [PATCH] Create: 0049-group-anagrams.scala --- scala/0049-group-anagrams.scala | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 scala/0049-group-anagrams.scala diff --git a/scala/0049-group-anagrams.scala b/scala/0049-group-anagrams.scala new file mode 100644 index 000000000..df5a05c5e --- /dev/null +++ b/scala/0049-group-anagrams.scala @@ -0,0 +1,30 @@ +import scala.collection.mutable.{Map => MMap} +object Solution { + def groupAnagrams(strs: Array[String]): List[List[String]] = { + val resultMap = MMap[MMap[Char, Int], List[String]]() + strs + .map(str => (str, letterCountMap(str))) + .foreach { tupled => + tupled match { + case (str, aMap) => { + resultMap.updateWith(aMap) { + case Some(listOfStrings) => Some(listOfStrings :+ str) + case None => Some(List(str)) + } + } + } + } + resultMap.values.toList + } + + def letterCountMap(str: String): MMap[Char, Int] = { + val map = MMap[Char, Int]() + str.foreach{ char => + map.updateWith(char){ + case Some(value) => Some(value + 1) + case None => Some(1) + } + } + map + } +}