---
description: https://leetcode.com/problems/custom-sort-string/
---

# 791. Custom Sort String

S中每个字母代表对应字母的顺序，对T以S中定义的顺序重排序。S中的字符相当于bucket sorting中的bucket，把T中字符放到对应的bucket即可。

```cpp
/*
 * @lc app=leetcode id=791 lang=cpp
 *
 * [791] Custom Sort String
 */

// @lc code=start
class Solution {
public:
    string customSortString(string S, string T) {
        vector<int> freqs(26, 0);
        for (const auto t : T) ++freqs[t - 'a'];
        string res(T.size(), ' ');
        int c = 0;
        for (const auto s : S) {
            for (int i = 0; i < freqs[s - 'a']; ++i) {
                res[c++] = s;
            }
            freqs[s - 'a'] = 0;
        }
        for (int i = 0; i < 26; ++i) {
            for (int j = 0; j < freqs[i]; ++j) {
                res[c++] = 'a' + i;
            }
        }
        return res;
    }
};
// @lc code=end


```
