A家的题。
解法1直接sort,
class Solution {
public:
string customSortString(string S, string T) {
if(S.empty()){
return T;
}
auto comp = [&S](const char c1, const char c2){
return S.find(c1) < S.find(c2);
};
sort(T.begin(), T.end(), comp);
return T;
}
};
解法二:记下string T中每个char的个数,然后再loop S, 按照S的顺序recover出来
class Solution {
public:
string customSortString(string S, string T) {
unordered_map<char, int> mp;
for(char c : T){
mp[c]++;
}
string ret = "";
for(char c : S){
if(mp.count(c)){
int cnt = mp[c];
ret += string(cnt, c);
mp.erase(c);
}
}
for(auto it : mp){
char c = it.first; int cnt = it.second;
ret += string(cnt, c);
}
return ret;
}
};
网友评论