LeetCode-Python-791. 自定义字符串排序

字符串S和 T 只包含小写字符。在S中,所有字符只会出现一次。

S 已经根据某种规则进行了排序。我们要根据S中的字符顺序对T进行排序。更具体地说,如果Sxy之前出现,那么返回的字符串中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
  • ST只包含小写字符。

第一种思路:

利用python 的自定义排序,从评论区学来的。

class Solution(object):
    def customSortString(self, S, T):
        """
        :type S: str
        :type T: str
        :rtype: str
        """
        return "".join(sorted(list(T), key = lambda x: S.find(x)))

第二种思路:

先统计一下T里字符出现的频率,然后遍历S,如果S里的字符在T里出现了,就把它放到res里。遍历完S后,再把T中没有排序要求的字符放到res里。

class Solution(object):
    def customSortString(self, S, T):
        """
        :type S: str
        :type T: str
        :rtype: str
        """
        res = ""
        c = collections.Counter(T)
        for char in S:
            if c.get(char, 0):
                res += char * c[char]
                c[char] = 0
                
        for key in c:
            if c[key] != 0:
                res += key * c[key]
        
        return res

第二种思路的优化:

class Solution(object):
    def customSortString(self, S, T):
        """
        :type S: str
        :type T: str
        :rtype: str
        """
        res = ""
        
        for char in S:
            res += char * T.count(char)
            
        for char in T:
            if char not in S:
                res += char
        
        return res

直接加就行了,还不用调collections.Couter()。

猜你喜欢

转载自blog.csdn.net/qq_32424059/article/details/88359964