Skip to content

Instantly share code, notes, and snippets.

@TerryCK
Created December 19, 2021 06:40
Show Gist options
  • Save TerryCK/3afc35ce9b7f2f6f275a007992715e7f to your computer and use it in GitHub Desktop.
Save TerryCK/3afc35ce9b7f2f6f275a007992715e7f to your computer and use it in GitHub Desktop.
Algorithms for Anagrams output
// brute force
func funWithAnagrams1(text: [String]) -> [String] {
var result = [String]()
var lookup = [Int: Set<Character>]()
for string in text {
if let set = lookup[string.count],
set.isSuperset(of: Array(string)) {
continue
} else {
lookup[string.count] = Set(string)
result.append(string)
}
}
return result.sorted()
}
// more detail and explore and use Set to reduce time of complexity.
func funWithAnagrams(text: [String]) -> [String] {
var result = [String]()
var lookup = [Int: [Set<Character>]]()
for string in text {
let array: Array<Character> = Array(string)
let currentStringSet: Set<Character> = Set(array)
if let sets = lookup[currentStringSet.count], sets.contains(where: { $0.count == currentStringSet.count}) {
for interSet in sets {
for target in string where !interSet.contains(target) {
break
}
}
} else {
if lookup[currentStringSet.count] != nil {
lookup[currentStringSet.count]?.append(currentStringSet)
} else {
lookup[currentStringSet.count] = [currentStringSet]
}
result.append(string)
}
}
return result.sorted()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment