7.68%
class Solution(object):
def customSortString(self, S, T):
"""
:type S: str
:type T: str
:rtype: str
"""
lists = []
result = ''
dicts = {}
for i,s in enumerate(S):
dicts[s] = i
for char in T:
if char in dicts.keys():
lists.append([char,dicts[char]])
else:
result += char
lists = sorted(lists,key = lambda x:x[1])
for i in lists:
result += i[0]
return result
————————————————————————
88.75% 很妙 直接用要求的顺序找char即可
class Solution(object):
def customSortString(self, S, T):
"""
:type S: str
:type T: str
:rtype: str
"""
result = []
for char in S:
result.append(char*T.count(char))
for char in T:
if char not in S:
result.append(char)
return ''.join(result)
——————————————————————
68.37% 主要学习一下字典的collections的Counter函数
from collections import Counter
class Solution(object):
def customSortString(self, S, T):
"""
:type S: str
:type T: str
:rtype: str
"""
result = ''
counts = Counter(T)
for char in S:
result += char*counts[char]
del counts[char]
for char,cnt in counts.items():
result += char*cnt
return ''.join(result)
————————————————————————
78.62% 又一个很巧妙的,主要是熟练运用sorted函数,而且不仅仅是list可以使用,string也是一个迭代器所以也是可以用。
注意sorted返回的是一个排好序的list,所以可以用join函数相连。
from collections import Counter
class Solution(object):
def customSortString(self, S, T):
"""
:type S: str
:type T: str
:rtype: str
"""
return ''.join(sorted(T,key= lambda x:S.index(x) if x in S else 26))
————————————————
59.8% 又一个抖机灵是可以直接把已经筛选过的字符换成空字符,就不用再循环一遍看看还有啥没有筛选过
from collections import Counter
class Solution(object):
def customSortString(self, S, T):
"""
:type S: str
:type T: str
:rtype: str
"""
result = ''
for char in S:
result += char*T.count(char)
T = T.replace(char,'')
return result+T