# Leetcode [No. 791] Custom Sort String (MEDIUM) 解題心得 ## 題目 https://leetcode.com/problems/custom-sort-string/ ## 思路 + 這個解法就是先用一個map去紀錄s出現過那些字母,各出現幾次。 + 接著照著order去填,有幾個就填幾個,最後再把剩下的填完。 ```c++= class Solution { public: string customSortString(string order, string s) { string res = ""; unordered_map<char,int> freqCnt; for(auto c: s) { freqCnt[c]++; } for(auto o: order) { if(freqCnt.count(o)) { while(freqCnt[o] > 0) { res += o; freqCnt[o]--; } freqCnt.erase(o); } } for(auto iter:freqCnt) { while(iter.second > 0) { res += iter.first; iter.second --; } } return res; } }; ``` ### 解法分析 + time complexity: O(n) ### 執行結果 ![image](https://hackmd.io/_uploads/SJbEKE26p.png)