解题思路
- 首先对s中出现的字母进行统计。
- 逐个遍历order中的字母,如果字母在order中,则将对应个数的这个字母加入到ans中。
- 最后将s中的剩余字母加到ans最后。
代码
class Solution:
def customSortString(self, order: str, s: str) -> str:
cnt = [0] * 26
# 对s中的字母进行统计
for c in s:
cnt[ord(c) - ord('a')] += 1
ans = ''
for c in order:
if cnt[ord(c) - ord('a')] > 0:
ans += c * cnt[ord(c) - ord('a')]
cnt[ord(c) - ord('a')] = 0
for i in range(26):
if cnt[i] > 0:
ans += chr(i + ord('a')) * cnt[i]
return ans