[LeetCode] Custom Sort String

791. Custom Sort String

You are given two strings order and s. All the words of order are unique and were sorted in some custom order previously.

Permute the characters of s so that they match the order that order was sorted. More specifically, if a character x occurs before a character y in order, then x should occur before y in the permuted string.

Return any permutation of s that satisfies this property.

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
string customSortString(string order, string s) {
int o = 1;
unordered_map<char, int> mp;
for(auto& ch : order)
mp[ch] = o++;
sort(begin(s), end(s), [&](char a, char b) {
return mp[a] < mp[b];
});
return s;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/03/PS/LeetCode/custom-sort-string/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.