Created
April 6, 2020 16:41
-
-
Save ChrisGuzman/7cea83ce50701a5d5cb940d35e732910 to your computer and use it in GitHub Desktop.
LeetCode 6 Group 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
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