# 791. Custom Sort String

`S` and `T` are strings composed of lowercase letters. In `S`, no letter occurs more than once.

`S` was sorted in some custom order previously. We want to permute the characters of `T` so that they match the order that `S` was sorted. More specifically, if `x` occurs before `y` in `S`, then `x` should occur before `y` in the returned string.

Return any permutation of `T` (as a string) that satisfies this property.

``````Example :
Input:
S = "cba"
T = "abcd"
Explanation:
"a", "b", "c" appear in S, so the order of "a", "b", "c" should be "c", "b", and "a".
Since "d" does not appear in S, it can be at any position in T. "dcba", "cdba", "cbda" are also valid outputs.
``````

Note:

• `S` has length at most `26`, and no character is repeated in `S`.
• `T` has length at most `200`.
• `S` and `T` consist of lowercase letters only.

``````class Solution {
public:
string customSortString(string S, string T) {
string res = "";
unordered_map<char, int> m;
for (char c : T) ++m[c];
for (char c : S) {
res += string(m[c], c);
m[c] = 0;
}
for (auto a : m) {
res += string(a.second, a.first);
}
return res;
}
};
``````

``````class Solution {
public:
string customSortString(string S, string T) {
string res = "";
vector<int> cnt(26, 0);
for (char c : T) ++cnt[c - 'a'];
for (char c : S) {
while (cnt[c - 'a']-- > 0) res.push_back(c);
}
for (char c : T) {
while (cnt[c - 'a']-- > 0) res.push_back(c);
}
return res;
}
};
``````

``````class Solution {
public:
string customSortString(string S, string T) {
sort(T.begin(), T.end(), [&](char a, char b) {return S.find(a) < S.find(b);});
return T;
}
};
``````

``````class Solution {
public:
string customSortString(string S, string T) {
unordered_map<char, int> m;
for (int i = 0; i < S.size(); ++i) {
m[S[i]] = i + 1;
}
sort(T.begin(), T.end(), [&](char a, char b) {return m[a] < m[b];});
return T;
}
};
``````

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

https://leetcode.com/problems/custom-sort-string/discuss/116556/Two-Lines-C++

https://leetcode.com/problems/custom-sort-string/discuss/116615/Java-5-ms-10-line-counting-solution-with-comment

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation