【题目】
字符串S和 T 只包含小写字符。在S中,所有字符只会出现一次。
S 已经根据某种规则进行了排序。我们要根据S中的字符顺序对T进行排序。更具体地说,如果S中x在y之前出现,那么返回的字符串中x也应出现在y之前。
返回任意一种符合条件的字符串T。
示例:
输入:
S = "cba"
T = "abcd"
输出: "cbad"
解释:
S中出现了字符 "a", "b", "c", 所以 "a", "b", "c" 的顺序应该是 "c", "b", "a".
由于 "d" 没有在S中出现, 它可以放在T的任意位置. "dcba", "cdba", "cbda" 都是合法的输出。
注意:
S的最大长度为26,其中没有重复的字符。 T的最大长度为200。 S和T只包含小写字符。
【思路】
对字符串T进行字符计数,再按照字符串S的顺序生成新的字符串。
【代码】
python版本
class Solution(object):
def customSortString(self, S, T):
"""
:type S: str
:type T: str
:rtype: str
"""
# ord() 字符转换为ascii码
# chr() ascii码转换为字符
count = [] *
for i, ti in enumerate(T):
count[ord(ti) - ] +=
res = ''
for i, si in enumerate(S):
res += si * count[ord(si) - ]
count[ord(si) - ] =
for i, ci in enumerate(count):
res += chr(i + ) * ci
return res
C++版本
class Solution {
public:
string customSortString(string S, string T) {
vector count(, );
for(int i=; i<T.size(); i++){
count[T[i] - 'a']++;
}
string res="";
for(int j=; j<S.size(); j++){
for(int k=; k<count[S[j] - 'a']; k++){
res += S[j];
}
count[S[j] - 'a'] = ;
}
for(int j=; j<count.size(); j++){
for(int k=; k<count[j]; k++){
res += ('a' + j);
}
}
return res;
}
};