【Leetcode_總結】791. 自定義字串排序 - python
阿新 • • 發佈:2019-01-07
Q:
字串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
只包含小寫字元。
連結: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