题目描述
分析
首先统计所有 character 频率于 map
遍历字符串,只要当前字符频率已存在 >= 2 次,降低频率,如果还存在,再此降低其频率,以此类推,直至 0
每次降低频率做一次记录,即递增 ret
算法
贪心
过程
统计频率,可以用 26 length 的数组做统计,每个位置设为 0
遍历字符串,查看当前字符的频率,如果当前频率需要减少,递减当前字符频率,并且递增 ret
代码
/**
* @param {string} s
* @return {number}
*/
var minDeletions = function(s) {
const map = new Array(26).fill(0)
let times = 0
for (const x of s) {
const code = x.charCodeAt() - 97
map[code] += 1
}
for (let i = 0; i < 26; i++) {
while (map[i] !== 0 && map.indexOf(map[i]) !== i) {
map[i]--
times++
}
}
return times
};