Created
June 25, 2018 14:02
-
-
Save digoreis/d7ba103c93b8c2e6f2a9055a2e4408d5 to your computer and use it in GitHub Desktop.
Implement an algorithm to determine if a string has all unique characters.
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
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