题目地址:
https://leetcode.com/problems/remove-letter-to-equalize-frequency/description/
给定一个长 n n n字符串 s s s,必须删一个字符,问能否将其每个字母频率变得相等。
情况较多,分类讨论即可。代码如下:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20class Solution { public: bool equalFrequency(string s) { if (s.empty()) return false; unordered_map<int, int> mp, freq; for (char ch : s) mp[ch]++; for (auto &[k, v] : mp) freq[v]++; if (freq.size() > 2) return false; if (freq.size() == 1) { auto &[k, v] = *freq.begin(); return k == 1 || v == 1; } if (freq.count(1) && freq[1] == 1) return true; for (auto &[k, v] : freq) if (v == 1 && freq.count(k - 1)) return true; return false; } };
时空复杂度 O ( n ) O(n) O(n)。
最后
以上就是冷静小刺猬最近收集整理的关于【Leetcode】2423. Remove Letter To Equalize Frequency题目地址:的全部内容,更多相关【Leetcode】2423.内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复