791. Custom Sort String
Medium
344112FavoriteShare
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.
class Solution {
public:
string customSortString(string S, string T) {
unordered_map<char,int> _map;
string Result = "";
for(char c : T){
_map[c] ++;
}
for(char c : S){
if(_map[c] > 0){
//--在Result的结尾处插入_map[c]个c
Result.insert(Result.length(),_map[c],c);
_map[c] = 0;
}
}
for(unordered_map<char,int>::iterator it = _map.begin();it != _map.end();it++){
if(it->first != 0){
Result.insert(Result.length(),it->second,it->first);
}
}
return Result;
}
};