3692. Majority Frequency Characters
思路分析
代码实现
import java.util.HashMap;
import java.util.Map;
class Solution {
public String majorityFrequencyGroup(String s) {
char[] arr = s.toCharArray();
HashMap<Character, Integer> charCountMap = new HashMap<>();
for (char c : arr) {
charCountMap.put(c, charCountMap.getOrDefault(c, 0) + 1);
}
HashMap<Integer, Integer> groupSizeMap = new HashMap<>();
for (int freq : charCountMap.values()) {
groupSizeMap.put(freq, groupSizeMap.getOrDefault(freq, 0) + 1);
}
int bestK = 0;
int maxGroupSize = 0;
for (int k : groupSizeMap.keySet()) {
int currentGroupSize = groupSizeMap.get(k);
if (currentGroupSize > maxGroupSize) {
maxGroupSize = currentGroupSize;
bestK = k;
}
else if (currentGroupSize == maxGroupSize) {
if (k > bestK) {
bestK = k;
}
}
}
StringBuilder sb = new StringBuilder();
for (char c : charCountMap.keySet()) {
if (charCountMap.get(c) == bestK) {
sb.append(c);
}
}
return sb.toString();
}
}
class Solution {
public String majorityFrequencyGroup(String s) {
int[] charCounts = new int[26];
for (char c : s.toCharArray()) {
charCounts[c - 'a']++;
}
HashMap<Integer, Integer> groupSizeMap = new HashMap<>();
for (int count : charCounts) {
if (count > 0) {
groupSizeMap.put(count, groupSizeMap.getOrDefault(count, 0) + 1);
}
}
int bestK = 0;
int maxGroupSize = 0;
for (int k : groupSizeMap.keySet()) {
int size = groupSizeMap.get(k);
if (size > maxGroupSize || (size == maxGroupSize && k > bestK)) {
maxGroupSize = size;
bestK = k;
}
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 26; i++) {
if (charCounts[i] == bestK) {
sb.append((char)('a' + i));
}
}
return sb.toString();
}
}
同类题型
视频讲解
💬 评论