Created
April 16, 2018 02:00
-
-
Save godrm/63fd06bba53484a92138c6449ec05d51 to your computer and use it in GitHub Desktop.
This file contains 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
func countByCharacter(_ value: String) -> [Character: Int] { | |
var countMap = [Character: Int]() | |
for char in value { | |
let count = countMap[char] ?? 0 | |
countMap[char] = count + 1 | |
} | |
return countMap | |
} | |
func isValid(_ countMap: [Character:Int]) -> Bool { | |
let allKeys = countMap.keys | |
var compareMap = [Int:Int]() | |
for key in allKeys { | |
let value = countMap[key] ?? 0 | |
let count = compareMap[value] ?? 0 | |
compareMap[value] = count + 1 | |
} | |
let countKeys = compareMap.keys | |
let minKey = countKeys.min() ?? 0 | |
let maxKey = countKeys.max() ?? 0 | |
let keyDiff = maxKey - minKey | |
let maxValue = compareMap[maxKey] ?? 0 | |
let lastOne = (compareMap[minKey] ?? 0)==1 && minKey==1 | |
return (compareMap.count == 1 | |
|| (compareMap.count == 2 && keyDiff == 1 && maxValue == 1) | |
|| (compareMap.count == 2 && lastOne)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you @godrm 👍 great solution. I can't solve the problem by myself after getting the dictionary with the count with each character.
HackerRank Problem:
Swift Solution there: