LeetCode-2423. 删除字符使频率相同

题目链接

LeetCode-2423. 删除字符使频率相同

题目描述

LeetCode-2423. 删除字符使频率相同_第1张图片

题解

题解一(Java)

作者:@仲景

class Solution {
    public boolean equalFrequency(String word) {

        // map
        int[] wordCount = new int[26];

        // 统计各个字母出现的次数
        int len = word.length();
        for (int i = 0; i < len; i++) {
            wordCount[word.charAt(i) - 'a']++;
        }

        // 遍历map
        for (int i = 0; i < wordCount.length; i++) {
            if (wordCount[i] == 0) {
                continue;
            }


            // 当前字符次数-1, 记录次数
            int count = --wordCount[i];
            // 所有字符是否次数都一样
            boolean isEqual = true;
            for (int j = 0; j < wordCount.length; j++) {
                if (wordCount[j] == 0) {
                    continue;
                }

                // 如果存在,且和当前字符-1后不一样,直接false
                if (count > 0 && wordCount[j] != count) {
                    isEqual = false;
                    break;
                }
                count = wordCount[j];
            }

            if (isEqual) {
                return true;
            }

            // 减掉的再加回去
            wordCount[i]++;
        }

        return false;
    }
}

你可能感兴趣的:(LeetCode,leetcode,算法,职场和发展)