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;
}
相关推荐
愚润求学28 分钟前
【递归、搜索与回溯】FloodFill算法(一)
c++·算法·leetcode
愚润求学3 小时前
【递归、搜索与回溯】FloodFill算法(二)
c++·算法·leetcode
南枝异客4 小时前
四数之和-力扣
java·算法·leetcode
hn小菜鸡7 小时前
LeetCode 2529.正整数和负整数的最大计数
java·算法·leetcode
hn小菜鸡8 小时前
LeetCode 2917.找出数组中的K-or值
数据结构·算法·leetcode
Once_day8 小时前
代码训练LeetCode(34)文本左右对齐
算法·leetcode·c
zhuiQiuMX8 小时前
SQL力扣
数据库·sql·leetcode
Tess_Blingbling9 小时前
力扣Hoot100 第一天 | 哈希3题
leetcode·哈希算法·散列表
好易学·数据结构9 小时前
可视化图解算法51:寻找第K大(数组中的第K个最大的元素)
数据结构·python·算法·leetcode·力扣·牛客网·堆栈
Once_day11 小时前
代码训练LeetCode(33)字符串首次匹配
算法·leetcode·c