Created
June 25, 2018 14:31
-
-
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.
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<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