返回顶部

2287

给你两个下标从 0 开始的字符串 s 和 target 。你可以从 s 取出一些字符并将其重排,得到若干新的字符串。

从 s 中取出字符并重新排列,返回可以形成 target 的 最大 副本数。

 

示例 1:

输入:s = "ilovecodingonleetcode", target = "code"
输出:2
解释:
对于 "code" 的第 1 个副本,选取下标为 4 、5 、6 和 7 的字符。
对于 "code" 的第 2 个副本,选取下标为 17 、18 、19 和 20 的字符。
形成的字符串分别是 "ecod" 和 "code" ,都可以重排为 "code" 。
可以形成最多 2 个 "code" 的副本,所以返回 2 。

class Solution(object):
    def rearrangeCharacters(self, s, target):
        """
        :type s: str
        :type target: str
        :rtype: int
        """
        ans = float('inf')
        count = [0]*26
        count_target = [0]*26
        for char in s:
            count[ord(char)%97] = count[ord(char)%97]+1
        for targetchar in target:
            count_target[ord(targetchar)%97] = count_target[ord(targetchar)%97]+1
        for targetchar in target:
            ans = min(ans,count[ord(targetchar)%97]//count_target[ord(targetchar)%97])
        return ans

 Guess 或许可以去学一下Counter这个函数

posted @ 2023-11-11 14:52  YuhangLiuCE  阅读(3)  评论(0编辑  收藏  举报