题目链接:https://leetcode.com/problems/custom-sort-string/description/
SandTare strings composed of lowercase letters. InS, no letter occurs more than once.
Swas sorted in some custom order previously. We want to permute the characters ofTso that they match the order thatSwas sorted. More specifically, ifxoccurs beforeyinS, thenxshould occur beforeyin 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:
Shas length at most26, and no character is repeated inS.Thas length at most200.SandTconsist 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
浙公网安备 33010602011771号