Created
December 19, 2021 06:40
-
-
Save TerryCK/3afc35ce9b7f2f6f275a007992715e7f to your computer and use it in GitHub Desktop.
Algorithms for Anagrams output
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
// 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