Skip to content

Instantly share code, notes, and snippets.

@digoreis
Created June 25, 2018 14:31
Show Gist options
  • Save digoreis/4f1e99e9df53e22af7b65a7b4a6e1a15 to your computer and use it in GitHub Desktop.
Save digoreis/4f1e99e9df53e22af7b65a7b4a6e1a15 to your computer and use it in GitHub Desktop.
Given two strings, a method to decide if one is permutation of the other.
import Cocoa
struct Counter {
var table = Dictionary<Character,Int>()
mutating func add(_ key: Character) {
let value = table[key] ?? 0
table[key] = value + 1
}
mutating func remove(_ key: Character) {
let value = table[key] ?? 0
table[key] = value - 1
}
func permutation() -> Bool {
return !table.values.contains(where: {$0 != 0})
}
}
func checkPermutation(word1: String, word2: String) -> Bool {
guard word1.count == word2.count else { return false }
var counter = Counter()
var iteratorW1 = word1.makeIterator()
var iteratorW2 = word2.makeIterator()
while let char1 = iteratorW1.next(), let char2 = iteratorW2.next() {
counter.add(char1)
counter.remove(char2)
}
return counter.permutation()
}
print(checkPermutation(word1: "abc", word2: "cba"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment