1. 程式人生 > >178.Custom Sort String

178.Custom Sort String

題目

S and T are strings composed of lowercase letters. In S, no letter occurs more than once.

S was sorted in some custom order previously. We want to permute the characters of T so that they match the order that S was sorted. More specifically, if x occurs before y in S, then x should occur before y 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 most 26, and no character is repeated in S.
T has length at most 200.
S and T consist of lowercase letters only.

連結

分析

問題轉化為根據S指定的順序輸出T對應的字串;
Step1:遍歷T中的字元,統計各個字元出現的次數,儲存在陣列tmp內;如a如果出現3次,則tmp[0] = 3; d出現兩次,則tmp[3] = 2;
Step2:遍歷S中的字元,找出對應的tmp對應下標對應的值,輸出幾次,如如遇T中字元為d,則列印2兩次d,然後tmp[3]置為0;
Step3:輸出tmp中不為0的元素對應的字元,如T中不包含y,但是tmp[24]=3,說明S中有3個y,則接著輸出3個y;

程式碼

 def customSortString(self, S, T):
        """
        :type S: str
        :type T: str
        :rtype: str
        """
        re = ""
        tmp = [0 for x in range(0, 26)] #定義一個有26個元素的初始值為0的陣列tmp
        for c in T:
            tmp[ord(c) - 97] += 1  #ord(c)求一個字元c的ASII值


        for c in S:
            while tmp[ord(c)-97]  > 0:
                re += c
                tmp[ord(c) - 97] -= 1


        for i in range (0, 26):
             while tmp[i]  > 0:
                    re += chr(i + 97) #chr(num) 轉換成ASII碼為num的字元
                    tmp[i] -= 1

        return re

python知識點

  • ord(c)求一個字元c的ASII值
  • chr(num) 轉換成ASII碼為num的字元