HJ23 删除字符串中出现次数最少的字符

72 阅读1分钟

image.png

const rl = require("readline").createInterface({ input: process.stdin });
var iter = rl[Symbol.asyncIterator]();
const readline = async () => (await iter.next()).value;

void (async function () {
    // Write your code here
    while ((line = await readline())) {
        const str = line.trim(); // 去除空格
        const map = new Map(); // 定义哈希表

        // 统计每个字符出现的次数
        for (let i = 0; i < str.length; i++) {
            const ch = str[i];
            map.set(ch, map.has(ch) ? map.get(ch) + 1 : 1); // 更新哈希表中的值
        }

        // 找出出现次数最小的字符
        let minFreq = Infinity;
        for (const freq of map.values()) {
            minFreq = Math.min(minFreq, freq);
        }

        // 删除出现次数最小的字符
        let res = "";
        for (let i = 0; i < str.length; i++) {
            const ch = str[i];
            if (map.get(ch) !== minFreq) {
                res += ch;
            }
        }

        console.log(res);
    }
})();

删除字符串中出现次数最少的字符_牛客题霸_牛客网 (nowcoder.com)