Skip to content

Instantly share code, notes, and snippets.

@digoreis
Created June 25, 2018 14:02
Show Gist options
  • Save digoreis/d7ba103c93b8c2e6f2a9055a2e4408d5 to your computer and use it in GitHub Desktop.
Save digoreis/d7ba103c93b8c2e6f2a9055a2e4408d5 to your computer and use it in GitHub Desktop.
Implement an algorithm to determine if a string has all unique characters.
import Cocoa
struct Counter {
var table = Dictionary<String,Int>()
mutating func insertUnique(_ word: String) -> Bool {
let value = table[word] ?? 0
guard value == 0 else { return false }
table[word] = value + 1
return true
}
}
func uniqueCharacters(_ word: String) -> Bool {
var counter = Counter()
for w in word {
if !counter.insertUnique(String(w)) {
return false
}
}
return true
}
print(uniqueCharacters("abcdefghi"))
print(uniqueCharacters("abcdefghii"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment