2024/4/1—力扣—删除字符使频率相同

代码实现:

思路:

步骤一:统计各字母出现频率

步骤二:频率从高到低排序,形成频率数组

步骤三:频率数组只有如下组合符合要求:

  • 1, 0...0
  • n + 1, n...n (, 0)
  • n...n, 1(, 0)
cpp 复制代码
bool equalFrequency(char *word) {
    if (word == NULL || strlen(word) == 0 || strlen(word) == 1) {
        return true;
    }
    int hash[26] = {0};
    for (int i = 0; i < strlen(word); i++) {
        hash[word[i] - 'a']++;
    }
    
    // 出现频率从大到小排序
    for (char i = 25; i > 0; i++) {
        for (char j = 0; j < 25; j++) {
            if (hash[j] < hash[j + 1]) {
                char temp = hash[j];
                hash[j] = hash[j + 1];
                hash[j + 1] = temp;
            }
        }
    }

    char type = 0;
    // type = 0: 检查 n, 0...0
    // type = 1: 检查 n + 1, n...n (, 0)
    // type = 2: 检查 n...n, 1(, 0)
    for (char i = 0; i < 26; i++) {
        if (type == 0) {
            if (!hash[i + 1]) {
                return true;
            } else if (hash[i] - 1 == hash[i + 1]) {
                type = 1;
            } else {
                type = 2;
            }
        } else if (type == 1) {
            if (hash[i] != hash[0] - 1) {
                return false;
            } else if (i == 25 || hash[i + 1] == 0) {
                return true;
            }
        } else if (type == 2) {
            if (hash[i] == 1 && (i == 25 || hash[i + 1] == 0)) {
                return true;
            } else if (hash[i] != hash[0]) {
                return false;
            }
        }
    }
    return false;
}
相关推荐
敲代码的嘎仔5 小时前
力扣高频SQL基础50题详解
开发语言·数据库·笔记·sql·算法·leetcode·后端开发
洛水水7 小时前
【力扣100题】46.单词拆分
算法·leetcode·职场和发展
alphaTao9 小时前
LeetCode 每日一题 2026/5/11-2026/5/17
算法·leetcode
洛水水9 小时前
【力扣100题】45.零钱兑换
算法·leetcode·职场和发展
YL2004042610 小时前
041二叉树的层序遍历
数据结构·leetcode·bfs
洛水水11 小时前
【力扣100题】47.最长递增子序列
算法·leetcode·职场和发展
_日拱一卒12 小时前
LeetCode:199二叉树的右视图
算法·leetcode·职场和发展
人道领域12 小时前
【LeetCode刷题日记】递归与回溯实战 257.二叉树的所有路径——一篇文章彻底搞懂回溯
开发语言·python·算法·leetcode
ulias21213 小时前
leetcode热题 - 7
数据结构·算法·leetcode
玛卡巴卡ldf13 小时前
【LeetCode 手撕算法】(动态规划)爬楼梯、杨辉三角、打家劫舍、完全平方数、零钱兑换、单词拆分、最长递增子序列、乘积最大子数组、分割等和子集
java·数据结构·算法·leetcode·动态规划·力扣