Skip to content

Instantly share code, notes, and snippets.

@hebertialmeida
Created November 20, 2014 15:27
Show Gist options
  • Save hebertialmeida/f0b949835ba157ad2bb9 to your computer and use it in GitHub Desktop.
Save hebertialmeida/f0b949835ba157ad2bb9 to your computer and use it in GitHub Desktop.
Finding the most common character in a string. Swift implementation.
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