题目链接:https://leetcode.com/problems/custom-sort-string/description/
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 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.Note:
S
has length at most26
, and no character is repeated inS
.T
has length at most200
.S
andT
consist of lowercase letters only.
此题利用python自带电池的OrderedDict非常好做,loop两遍这个dict就可以了,不敢相信是medium。。。
代码如下:
class Solution(object):
def customSortString(self, S, T):
"""
:type S: str
:type T: str
:rtype: str
"""
d = collections.OrderedDict()
for c in S:
d[c] = ''
for c in T:
if c in d:
d[c] += c
else:
d[c] = c
res = ''
for k,v in d.iteritems():
res += v
return res