1. 程式人生 > >【Leetcode_總結】791. 自定義字串排序 - python

【Leetcode_總結】791. 自定義字串排序 - python

Q:

字串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只包含小寫字元。

連結:https://leetcode-cn.com/problems/custom-sort-string/description/

思路:思路是 統計在S中的字元s在T中的出現次數,res為s*T.count(s),遍歷完S後,T中剩下的字元放在res後就好了

程式碼:

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