3692. 眾數頻率字符

簡單 數組

思路

  1. 計算每個字元出現的次數,因為僅有英文小寫字母,用數組紀錄即可。
  2. 把出現次數相同的字元合併成一個字串,選出最長的那一個字串,如果長度相同,選出現次數高的。

用哈希表紀錄,鍵是出現次數,值是對應的合併字串。

程式碼

class Solution {
public:
    string majorityFrequencyGroup(string s) {
        int cnt[26]{};
        for(char c : s) ++cnt[c - 'a']; // 紀錄出現次數

        unordered_map<int, string> freq;
        for(int i = 0; i < 26; ++i) { // 合併字串
            if(cnt[i]) {
                freq[cnt[i]] += (i + 'a');            
            }
        }

        int curKey = 0;
        string curValue;
        for(auto [key, value] : freq) { // 找出最長的字串,若相等,選頻率高的。
            if(value.length() > curValue.length()) {
                curKey = key;
                curValue = value;
            }
            else if(value.length() == curValue.length() && key > curKey) {
                curKey = key;
                curValue = value;
            }
        }
        return curValue;
    }
};

複雜度分析

  • 時間複雜度:O(n)O(n)
  • 空間複雜度:O(n)O(n)

顯示設定

背景線條
顯示背景網格線條
懸停發光
滑鼠懸停時顯示霓虹效果
聚光燈
跟隨滑鼠的聚光燈效果
背景透明度
開啟透明玻璃效果
主題顏色
自訂主要顏色