我是靠谱客的博主 忧虑钢铁侠,最近开发中收集的这篇文章主要介绍LeetCode-451. Sort Characters By Frequency [C++][Java]题目描述解题思路,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

LeetCode-451. Sort Characters By FrequencyLevel up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.https://leetcode.com/problems/sort-characters-by-frequency/

题目描述

Given a string s, sort it in decreasing order based on the frequency of the characters. The frequency of a character is the number of times it appears in the string.

Return the sorted string. If there are multiple answers, return any of them.

Example 1:

Input: s = "tree"
Output: "eert"
Explanation: 'e' appears twice while 'r' and 't' both appear once.
So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer.

Example 2:

Input: s = "cccaaa"
Output: "aaaccc"
Explanation: Both 'c' and 'a' appear three times, so both "cccaaa" and "aaaccc" are valid answers.
Note that "cacaca" is incorrect, as the same characters must be together.

Example 3:

Input: s = "Aabb"
Output: "bbAa"
Explanation: "bbaA" is also a valid answer, but "Aabb" is incorrect.
Note that 'A' and 'a' are treated as two different characters.

Constraints:

  • 1 <= s.length <= 5 * 105
  • s consists of uppercase and lowercase English letters and digits.

解题思路

【C++】

1. priority_queue + map

class Solution {
public:
    string frequencySort(string s) {
        priority_queue<pair<int,char>> pq;
        unordered_map<char,int> mp;
        for (int i=0; i<s.size(); i++) {mp[s[i]]++;}
        for (auto it : mp) {pq.push({it.second, it.first});}
        string res = "";
        while (!pq.empty()) {
            pair<int,char> ft = pq.top(); pq.pop();
            res.append(ft.first, ft.second);
        }
        
        return res;
    }
};

2. pair数组 桶排序

class Solution {
public:
    string frequencySort(string s) {
        auto cmp = [](const pair<char,int>& x, const pair<char,int>& y) {
            return x.second == y.second ? y.first > x.first : x.second > y.second;
        };
        int i = 0;
        string result = "";
        pair<char,int> temp[128] = {}; 
        for (int i = 0;i < s.length();i++){
            ++temp[s[i]].second;
            temp[s[i]].first = char(s[i]);
        }
        sort(temp, temp + 128, cmp);
        for (int i=0; i < 128;i++){
            if (temp[i].second != 0){
                result.append(temp[i].second, temp[i].first);
            }
        }
        return result;
    }
};

【Java】

1. StringBuilder数组

class Solution {
    public String frequencySort(String s) {
        char[] cs = s.toCharArray();
        Arrays.sort(cs);
        StringBuilder sb = new StringBuilder();
        List<StringBuilder> sbList = new ArrayList<>();
        for (int i = 0 ; i < cs.length; i ++) {
            if (i > 0 && cs[i] != cs[i - 1]) {
                sbList.add(sb);
                sb = new StringBuilder();
            }
            sb.append(cs[i]);
        }
        sbList.add(sb);
        sbList.sort((a, b) -> {return b.length() - a.length();});
        String res = "";
        for (StringBuilder sbr : sbList)
            res += sbr.toString();
        return res;
    }
}

2. 快排

class Solution {
    public String frequencySort(String s) {
        HashMap<Character,Integer> map = new HashMap(); 
        for(char ch : s.toCharArray()){
            map.put(ch,map.getOrDefault(ch,0)+1);
        } 
        char[] arr = new char[map.size()];
        int i=0 ; 
        for(char ch : map.keySet()){
            arr[i] = ch ; 
            i++;
        }
        quicksort(arr,0,arr.length-1,map);
        char[] ans = new char[s.length()];
        i=0 ; 
        for(char ch : arr){
            int count = map.get(ch);
            while(count-->0) {ans[i++] = ch;}
        }
        return new String(ans);
    }
    
    void quicksort(char[] arr, int l, int r, HashMap<Character,Integer> map){
        if (l>=r) return ;
        int part = partition(arr,l,r,map);
        quicksort(arr, l, part-1, map);
        quicksort(arr, part+1, r, map);
        return; 
    }
    
    int partition(char[] arr, int l, int r, HashMap<Character,Integer> map){
        char piv = arr[r]; 
        int curr = l; 
        for (int i=l; i<=r ; i++) {
            if (map.get(arr[i])>map.get(piv)) {
                swap(arr,curr,i);
                curr++;
            }
        }
        swap(arr,curr,r);
        return curr ; 
    }
    
    void swap(char[] arr, int a, int b){ 
        char temp = arr[a];
        arr[a] = arr[b];
        arr[b] = temp ;
    }
}

3. 大堆 桶排序

class Solution {
    public String frequencySort(String s) {
        if (s.length() == 1) return s;
        Map<Character, Integer> count = new HashMap<>();
        for (char c : s.toCharArray()) {count.put(c, count.getOrDefault(c, 0) + 1);}
        Queue<Character> maxHeap =
            new PriorityQueue<>((a,b) -> count.get(b).compareTo(count.get(a)));
        for (char c : count.keySet()) {maxHeap.add(c);}
        StringBuilder res = new StringBuilder();
        while (!maxHeap.isEmpty()) {
            char curr = maxHeap.poll();
            for (int i = 0; i < count.get(curr); i++) {
                res.append(curr);
            }
        }
        return res.toString();
    }
}

【1】c++中sort函数的compare_EricLee23-CSDN博客_sort函数compare

最后

以上就是忧虑钢铁侠为你收集整理的LeetCode-451. Sort Characters By Frequency [C++][Java]题目描述解题思路的全部内容,希望文章能够帮你解决LeetCode-451. Sort Characters By Frequency [C++][Java]题目描述解题思路所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(62)

评论列表共有 0 条评论

立即
投稿
返回
顶部