You are viewing a single comment's thread. Return to all comments →
My solution is rather different and uses (mutable) dictionaries:
func makeAnagram(a: String, b: String) -> Int { var aChars = getCharsDict(a: a) var bChars = getCharsDict(a: b) return compareAndUpdate(main: &aChars, comparison: &bChars) + compareAndUpdate(main: &bChars, comparison: &aChars) } private func getCharsDict(a: String) -> [Character: Int] { return a.reduce([Character: Int](), { (dict, char) in return dict.merging([char: 1], uniquingKeysWith: { $0 + $1 }) }) } private func compareAndUpdate(main: inout [Character: Int], comparison: inout [Character: Int]) -> Int { return main.reversed().reduce(0, { (sum, el) in main.removeValue(forKey: el.key) let otherElement = comparison.removeValue(forKey: el.key) ?? 0 return sum + abs(el.value - otherElement) }) }
Seems like cookies are disabled on this browser, please enable them to open this website
Strings: Making Anagrams
You are viewing a single comment's thread. Return to all comments →
My solution is rather different and uses (mutable) dictionaries: