/*
难度:中等
给定一个字符串,请将字符串里的字符按照出现的频率降序排列。
输出结果中,相同的字符必须放在一起。英文字母区分大小写
示例 1:
输入:tree
输出:eert 或者 eetr
*/
extension Daily {
static func test_leetcode451() {
let cases = [
"tree",
"cccaaa",
"Aabb",
]
for string in cases {
print("输入:\(string)")
let res = Daily.leetcode451(s: string)
print("输出:\(res)\n")
}
}
static func leetcode451(s: String) -> String {
if s.count < 3 {
return s
}
var map: [Character:Int] = [Character:Int]()
for cha in s {
map[cha] = (map[cha] ?? 0) + 1
}
let sorted = map.sorted{ $0.value > $1.value}
// print(sorted)
var result = ""
for (key, value) in sorted {
result += String(repeating: key, count: value)
}
return result
}
}
【LeetCode 451】根据字符出现频率排序
最新推荐文章于 2021-12-30 11:20:02 发布