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.
Example : Input: S = "cba" T = "abcd" Output: "cbad" 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.
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;
}
};
string容器的insert函数用法的链接:https://blog.csdn.net/qq_37437983/article/details/80066456