跳转至

1941. 检查是否所有字符出现次数相同

题目描述

给你一个字符串 s ,如果 s 是一个  字符串,请你返回 true ,否则请返回 false 。

如果 s 中出现过的 所有 字符的出现次数 相同 ,那么我们称字符串 s 是  字符串。

 

示例 1:

输入:s = "abacbc"
输出:true
解释:s 中出现过的字符为 'a','b' 和 'c' 。s 中所有字符均出现 2 次。

示例 2:

输入:s = "aaabb"
输出:false
解释:s 中出现过的字符为 'a' 和 'b' 。
'a' 出现了 3 次,'b' 出现了 2 次,两者出现次数不同。

 

提示:

  • 1 <= s.length <= 1000
  • s 只包含小写英文字母。

解法

方法一:计数

我们用一个哈希表或者一个长度为 \(26\) 的数组 \(\textit{cnt}\) 记录字符串 \(s\) 中每个字符出现的次数。

接下来遍历 \(\textit{cnt}\) 中的每个值,判断所有非零值是否相等即可。

时间复杂度 \(O(n)\),空间复杂度 \(O(|\Sigma|)\)。其中 \(n\) 是字符串 \(s\) 的长度;而 \(\Sigma\) 是字符集大小,本题中字符集为小写英文字母,因此 \(|\Sigma|=26\)

1
2
3
class Solution:
    def areOccurrencesEqual(self, s: str) -> bool:
        return len(set(Counter(s).values())) == 1
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
    public boolean areOccurrencesEqual(String s) {
        int[] cnt = new int[26];
        for (char c : s.toCharArray()) {
            ++cnt[c - 'a'];
        }
        int v = 0;
        for (int x : cnt) {
            if (x == 0) {
                continue;
            }
            if (v > 0 && v != x) {
                return false;
            }
            v = x;
        }
        return true;
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
    bool areOccurrencesEqual(string s) {
        vector<int> cnt(26);
        for (char c : s) {
            ++cnt[c - 'a'];
        }
        int v = 0;
        for (int x : cnt) {
            if (x == 0) {
                continue;
            }
            if (v && v != x) {
                return false;
            }
            v = x;
        }
        return true;
    }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
func areOccurrencesEqual(s string) bool {
    cnt := [26]int{}
    for _, c := range s {
        cnt[c-'a']++
    }
    v := 0
    for _, x := range cnt {
        if x == 0 {
            continue
        }
        if v > 0 && v != x {
            return false
        }
        v = x
    }
    return true
}
1
2
3
4
5
6
7
8
function areOccurrencesEqual(s: string): boolean {
    const cnt: number[] = Array(26).fill(0);
    for (const c of s) {
        ++cnt[c.charCodeAt(0) - 'a'.charCodeAt(0)];
    }
    const v = cnt.find(v => v);
    return cnt.every(x => !x || v === x);
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
    /**
     * @param String $s
     * @return Boolean
     */
    function areOccurrencesEqual($s) {
        $cnt = array_fill(0, 26, 0);
        for ($i = 0; $i < strlen($s); $i++) {
            $cnt[ord($s[$i]) - ord('a')]++;
        }
        $v = 0;
        foreach ($cnt as $x) {
            if ($x == 0) {
                continue;
            }
            if ($v && $v != $x) {
                return false;
            }
            $v = $x;
        }
        return true;
    }
}

评论