Given a string, sort it in decreasing order based on the frequency of characters.
Example:
Input: str = "tree"
Output: "eert"
Approach
Java
import java.util.Comparator;import java.util.HashMap;import java.util.LinkedHashMap;import java.util.Map;import java.util.stream.Collectors;public class SortCharactersByFrequency {public static void main(String[] args) {String str = "tree";System.out.println(frequencySort(str));}// function to sort the string// according to the frequencystatic String frequencySort(String s) {HashMap<Character, Integer> map = new HashMap<Character, Integer>();// count the frequency of each chararctersfor (int i = 0; i < s.length(); i++)map.put(s.charAt(i), map.getOrDefault(s.charAt(i), 0) + 1);// sort map by value decending orderMap<Character, Integer> result = map.entrySet().stream().sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,(oldV, newV) -> oldV, LinkedHashMap::new));StringBuffer sb = new StringBuffer();for (Character c : result.keySet()) {int cnt = result.get(c);while (cnt > 0) {cnt--;sb.append(c);}}return sb.toString();}}
C++
#include <bits/stdc++.h>using namespace std;//function to sort the string//according to the frequencystring frequencySort(string s){unordered_map<char, int> ump;//count the frequency of each chararctersfor (int i = 0; i < s.size(); i++)ump[s[i]]++;//max priority queuepriority_queue<pair<int, char>> pq;//push into the priority queuefor (auto p : ump)pq.push({p.second, p.first});string res = "";//make the string by//adding the charcters whose frequency is more//first then the characters whose frequecy is lesswhile (!pq.empty()){auto p = pq.top();pq.pop();while (p.first--)res += p.second;}return res;}int main(){string str = "tree";cout << frequencySort(str);return 0;}
No comments:
Post a Comment