先根据S给一个比较大小的字典,然后再把T排序。
class Solution {
public:
string customSortString(string S, string T) {
string res = "";
map<char,int> index;
for (int i = 0; i < S.length(); i++) index[S[i]] = i;
for (int i = 0; i < T.length(); i++)
{
if (!index.count(T[i])) res = res + T[i];
else {
int j = 0;
while ((index[T[i]] > index[res[j]])&&(j<res.length())) j++;
res.insert(j, T.substr(i,1));
}
}
return res;
}
};
另一种写法,自定义sort:
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;
}
};
还有一种写法是传一个函数名,参考这里。
以上两种方法都不是最快的,最快的方法是统计T中每个字母出现的次数然后直接根据字典添加对应次数的字母:
class Solution {
public:
string customSortString(string S, string T) {
unordered_map<char, int> counts;
for(auto ch : T)
counts[ch]++;
vector<char> sol;
for(auto ch : S)
while(counts[ch]--)
sol.push_back(ch);
for(auto ch : T)
if( counts[ch] > 0 )
sol.push_back(ch);
return string(sol.begin(), sol.end());
}
};