题目:
S
andT
are strings composed of lowercase letters. InS
, no letter occurs more than once.
S
was sorted in some custom order previously. We want to permute the characters ofT
so that they match the order thatS
was sorted. More specifically, ifx
occurs beforey
inS
, thenx
should occur beforey
in the returned string.
Return any permutation ofT
(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.
Note:
S
has length at most 26, and no character is repeated inS
.
T
has length at most200
.
S
andT
consist of lowercase letters only.
解释:
T
可以有无数多种满足条件的排序,一种最简单的排序方法是先把出现在S
中的字母写上,在写上没有出现在S
中的字母,出现的次数可以用Counter()
统计。
python代码:
from collections import Counter
class Solution(object):
def customSortString(self, S, T):
"""
:type S: str
:type T: str
:rtype: str
"""
c=Counter(T)
return ''.join([c[i]*i for i in S])+''.join([c[i]*i for i in c if i not in S])
c++代码:
#include<map>
using namespace std;
class Solution {
public:
string customSortString(string S, string T) {
map<char,int>countT;
for (auto t:T)
countT[t]+=1;
string result="";
for(auto s:S)
{
result+=string(countT[s],s);
}
for(auto item:countT)
{
if (S.find(item.first)==string::npos)
result+=string(item.second,item.first);
}
return result;
}
};
总结: