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;
}
相关推荐
设计师小聂!6 小时前
力扣热题100------136.只出现一次的数字
数据结构·算法·leetcode
崎岖Qiu6 小时前
leetcode643:子数组最大平均数 I(滑动窗口入门之定长滑动窗口)
java·算法·leetcode·力扣·双指针·滑动窗口
flashlight_hi7 小时前
LeetCode 分类刷题:2824. 统计和小于目标的下标对数目
javascript·数据结构·算法·leetcode
এ᭄画画的北北11 小时前
力扣-11.盛最多水的容器
算法·leetcode
Dream it possible!13 小时前
LeetCode 面试经典 150_数组/字符串_O(1)时间插入、删除和获取随机元素(12_380_C++_中等)(哈希表)
c++·leetcode·面试·哈希表
快去睡觉~13 小时前
力扣137:只出现一次的数字Ⅱ
数据结构·算法·leetcode
qq_5139704414 小时前
力扣 hot100 Day67
算法·leetcode·职场和发展
Cx330❀15 小时前
【数据结构初阶】--单链表(二)
数据结构·经验分享·算法·leetcode
weisian15115 小时前
力扣经典算法篇-45-回文数(数字处理:求余+整除,字符串处理:左右指针)
算法·leetcode·职场和发展
我想吃烤肉肉17 小时前
leetcode-python-删除链表的倒数第 N 个结点
python·算法·leetcode·链表