[11.13] 791. 自定义字符串排序

题目链接

解题思路

  1. 首先对s中出现的字母进行统计。
  2. 逐个遍历order中的字母,如果字母在order中,则将对应个数的这个字母加入到ans中。
  3. 最后将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

猜你喜欢

转载自blog.csdn.net/leeyns/article/details/127832224