Leetcode 2716. Minimize String Length
You are given a string s
which contains only lowercase letters. You need to perform the following operation as many times as possible to minimize the length of the string:
Return the minimized length of the string after performing the operation as many times as possible.
s
?0
?Assuming standard constraints:
s
is between 1
and 10^5
.s
contains only lowercase English letters.import java.util.HashMap;
import java.util.Map;
class Solution {
public int minimizeStringLength(String s) {
// Step 1: Calculate frequency of each character
Map<Character, Integer> frequencyMap = new HashMap<>();
for (char c : s.toCharArray()) {
frequencyMap.put(c, frequencyMap.getOrDefault(c, 0) + 1);
}
// Step 2: Identify most frequent character and reduce the string length
int totalLength = s.length();
while (!frequencyMap.isEmpty()) {
// Find the character with the highest frequency
char mostFrequentChar = ' ';
int highestFrequency = 0;
for (Map.Entry<Character, Integer> entry : frequencyMap.entrySet()) {
if (entry.getValue() > highestFrequency) {
mostFrequentChar = entry.getKey();
highestFrequency = entry.getValue();
}
}
// Remove all occurrences of the most frequent character
totalLength -= highestFrequency;
frequencyMap.remove(mostFrequentChar);
}
return totalLength;
}
}
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?