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;
}
相关推荐
无聊的小坏坏15 分钟前
单调栈通关指南:从力扣 84 到力扣 42
c++·算法·leetcode
qq_5139704416 小时前
力扣 hot100 Day37
算法·leetcode
不見星空16 小时前
leetcode 每日一题 1865. 找出和为指定值的下标对
算法·leetcode
chao_78919 小时前
回溯题解——子集【LeetCode】二进制枚举法
开发语言·数据结构·python·算法·leetcode
GEEK零零七20 小时前
Leetcode 1070. 产品销售分析 III
sql·算法·leetcode
凌肖战20 小时前
力扣网编程274题:H指数之普通解法(中等)
算法·leetcode
Y1nhl1 天前
力扣_链表_python版本
开发语言·python·算法·leetcode·链表·职场和发展
Swift社区1 天前
Swift 解 LeetCode 320:一行单词有多少种缩写可能?用回溯找全解
开发语言·leetcode·swift
YuTaoShao1 天前
【LeetCode 热题 100】48. 旋转图像——转置+水平翻转
java·算法·leetcode·职场和发展
百年孤独_2 天前
LeetCode 算法题解:链表与二叉树相关问题 打打卡
算法·leetcode·链表