思路
- 計算每個字元出現的次數,因為僅有英文小寫字母,用數組紀錄即可。
- 把出現次數相同的字元合併成一個字串,選出最長的那一個字串,如果長度相同,選出現次數高的。
用哈希表紀錄,鍵是出現次數,值是對應的合併字串。
程式碼
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;
}
};
複雜度分析
- 時間複雜度:
- 空間複雜度: