Created
August 8, 2022 17:02
-
-
Save Husseinhj/0ec6f464eb56e955993e2a778872cabd to your computer and use it in GitHub Desktop.
Group Anagrams
This file contains hidden or 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
package org.kotlinlang.play | |
fun main() { | |
val sample = listOf("eat","tea","tan","ate","nat","bat") | |
println(anagrams(sample)) | |
} | |
fun anagrams(words: List<String>): List<List<String>> { | |
val hashMap = hashMapOf<String, List<String>>() | |
words.forEach { word -> | |
val newWord = word.toCharArray().sortedArray().concatToString() | |
if (hashMap.containsKey(newWord)) { | |
val list = hashMap[newWord] ?: listOf() | |
val muList = list.toMutableList() | |
muList.add(word) | |
hashMap[newWord] = muList | |
} else { | |
hashMap[newWord] = listOf(word) | |
} | |
} | |
return hashMap.keys.map { | |
hashMap[it]!! | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Playgound:
https://pl.kotl.in/HJhIhjeNg