A string
Given a string
s
is called good if there are no two different characters in s
that have the same frequency.Given a string
s
, return the minimum number of characters you need to delete to make s
good.Example 1:
Input: s = "aaabbbcc"
Output: 2
Approach
Java
import java.util.HashSet;public class MakeCharacterFrequenciesUnique {public static void main(String[] args) {String s = "aaabbbcc";System.out.println(minDeletions(s));}// function to count minimum// deletions to make the frequency of// each characters as uniquestatic int minDeletions(String s) {int f[] = new int[26];for (int i = 0; i < s.length(); i++)f[s.charAt(i) - 'a']++;int cnt = 0;HashSet<Integer> st = new HashSet<Integer>();for (int i = 0; i < 26; i++) {if (f[i] > 0) {if (st.contains(f[i])) {cnt++;int x = f[i] - 1;int len = st.size();st.add(x);while (x > 0 && st.size() == len) {len = st.size();x--;st.add(x);cnt++;}} elsest.add(f[i]);}}return cnt;}}
C++
#include <bits/stdc++.h>using namespace std;//function to count minimum//deletions to make the frequency of//each characters as uniqueint minDeletions(string s){int f[26]={0};for(int i=0;i<s.size();i++)f[s[i]-'a']++;int cnt=0;set<int> st;for(int i=0;i<26;i++){if(f[i]>0){if(st.find(f[i])!=st.end()){cnt++;int x=f[i]-1;int len=st.size();st.insert(x);while(x>0&&st.size()==len){len=st.size();x--;st.insert(x);cnt++;}}elsest.insert(f[i]);}}return cnt;}int main(){string s = "aaabbbcc";cout<<minDeletions(s);return 0;}
No comments:
Post a Comment