我试图找到最强简洁,简短,简洁的方式来表达算法,找到字符串中最常出现的字符。
我的算法如下:
答案 0 :(得分:2)
基于@hennes解决方案,甚至还有一个更短的解决方案:
let string = "abbcde"
var counters = [Character: Int]()
for c in string.characters {
counters[c] = (counters[c] ?? 0) + 1
}
let maxElement = counters.reduce(counters.first!) { $1.1 > $0.1 ? $1 : $0 }
print(maxElement.0) // prints "b"
答案 1 :(得分:1)
您可以将字符本身用作字典的键。
let string = "abbcde"
var counters = [Character: Int]()
for c in string.characters {
if let count = counters[c] {
counters[c] = count + 1
} else {
counters[c] = 1
}
}
let maxElement = counters.reduce(counters.first!) { $1.1 > $0.1 ? $1 : $0 }
print(maxElement.0) // prints "b"
答案 2 :(得分:0)
这只会迭代序列一次:
extension SequenceType where Generator.Element : Hashable {
func mostFrequent() -> Generator.Element? {
var freqs: [Generator.Element:Int] = [:]
return maxElement { (bc, ec) in
let en = freqs[ec]?.successor() ?? 1
freqs[ec] = en
return en > freqs[bc]
}
}
}
"aabcccdee" // "c"
.characters
.mostFrequent()
或者,如果你想成为真正的高尔夫球手:
extension SequenceType where Generator.Element : Hashable {
func mostFrequent() -> Generator.Element? {
var fs: [Generator.Element:Int] = [:]
return maxElement { (bc, ec) in fs[ec]?++ ?? fs.updateValue(1, forKey: ec) >= fs[bc] }
}
}
"aaaabcccdee"
.characters
.mostFrequent()
方法之外:
var fs: [Character:Int] = [:]
let mostFrequent = "aaaeabcceced".characters
.maxElement { (bc, ec) in fs[ec]?++ ?? fs.updateValue(1, forKey: ec) >= fs[bc] }