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;
}
相关推荐
Mr_Xuhhh6 小时前
项目需求分析(2)
c++·算法·leetcode·log4j
Morri37 小时前
[Java恶补day53] 45. 跳跃游戏Ⅱ
java·算法·leetcode
林木辛7 小时前
LeetCode热题 15.三数之和(双指针)
算法·leetcode·双指针
和光同尘@10 小时前
66. 加一 (编程基础0到1)(Leetcode)
数据结构·人工智能·算法·leetcode·职场和发展
CHEN5_0210 小时前
leetcode-hot100 11.盛水最多容器
java·算法·leetcode
songx_9910 小时前
leetcode18(无重复字符的最长子串)
java·算法·leetcode
Lris-KK12 小时前
【Leetcode】高频SQL基础题--1341.电影评分
sql·leetcode
B612 little star king13 小时前
力扣29. 两数相除题解
java·算法·leetcode
野犬寒鸦13 小时前
力扣hot100:环形链表(快慢指针法)(141)
java·数据结构·算法·leetcode·面试·职场和发展
Miraitowa_cheems13 小时前
LeetCode算法日记 - Day 38: 二叉树的锯齿形层序遍历、二叉树最大宽度
java·linux·运维·算法·leetcode·链表·职场和发展