Leetcode 2423. Remove Letter To Equalize Frequency

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Remove Letter To Equalize Frequency

2. Solution

解析:Version 1,首先统计各字符数量,被移除的字符只有两种情况,移除一个字符数量为1的字符,移除一个数量最大的字符,然后分别判断剩下的字符频率是否相等。

  • Version 1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution:
def equalFrequency(self, word: str) -> bool:
stat = {}
for ch in word:
stat[ch] = stat.get(ch, 0) + 1

count = list(stat.values())
count.sort()

if count[0] - 1 == 0:
if len(set(count[1:])) == 1:
return True
count[-1] -= 1
if len(set(count)) == 1:
return True
return False

Reference

  1. https://leetcode.com/problems/remove-letter-to-equalize-frequency/
如果有收获,可以请我喝杯咖啡!