Skip to content

Instantly share code, notes, and snippets.

@ChrisGuzman
Created April 6, 2020 16:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ChrisGuzman/7cea83ce50701a5d5cb940d35e732910 to your computer and use it in GitHub Desktop.
Save ChrisGuzman/7cea83ce50701a5d5cb940d35e732910 to your computer and use it in GitHub Desktop.
LeetCode 6 Group Anagrams
fun main(args: Array<String>) {
groupAnagrams(arrayOf("eat", "tea", "tan", "ate", "nat", "bat"))
}
fun groupAnagrams(strs: Array<String>): List<List<String>> {
//Loop through array
val myMap = mutableMapOf<String, MutableList<String>>()
strs.forEach {
//take word and put in alphabetical order
val alphaOrdered = it.toCharArray().sorted().joinToString("")
//use alphabetized string as hash key
//set has value to word
val theValue = myMap[alphaOrdered]
if (theValue == null) {
myMap[alphaOrdered] = mutableListOf(it)
} else {
myMap[alphaOrdered]?.add(it)
}
}
//make list of list of values for each key in hash
return myMap.values.toList()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment