Created
November 20, 2014 15:27
-
-
Save hebertialmeida/f0b949835ba157ad2bb9 to your computer and use it in GitHub Desktop.
Finding the most common character in a string. Swift implementation.
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
import UIKit | |
var str = "aaaabbbaaaa * bbbb b bbbbbbb ccccccccdd ddddddd dddd" | |
var cnt = [String: Int]() | |
var i = 0 | |
for char in str { | |
var c = String(char) | |
if let match = cnt[c] { | |
cnt[c] = cnt[c]!+1 | |
} else { | |
cnt[c] = 1 | |
} | |
i++ | |
} | |
let sortedKeys = (cnt as NSDictionary).keysSortedByValueUsingSelector("compare:") | |
let key = sortedKeys.last! as NSString | |
println(key) | |
// Returns "B" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment