LeetCode每日一题:重温hashmap()的使用

2023-01-12  本文已影响0人  ShowMeCoding
2287. 重排字符形成目标字符串

给你两个下标从 0 开始的字符串 s 和 target 。你可以从 s 取出一些字符并将其重排,得到若干新的字符串。
从 s 中取出字符并重新排列,返回可以形成 target 的 最大 副本数。

输入: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:
    def rearrangeCharacters(self, s: str, target: str) -> int:
        s_count = {}
        t_count = {}
        res = 100     # target最小长度
        for ss in s:
            if ss in target:
                if ss in s_count:
                    s_count[ss] += 1
                else:
                    s_count[ss] = 1
        for tt in target:
            if tt in t_count:
                t_count[tt] += 1
            else:
                t_count[tt] = 1
        if len(s_count) != len(t_count):
            return 0
        else:
            # 求最小倍数,除数取整
            for k in s_count.keys():
                res = min(res, s_count[k]//t_count[k])
        return res
class Solution:
    def rearrangeCharacters(self, s: str, target: str) -> int:
        # 字典统计
        s_count = dict(Counter(s))
        t_count = dict(Counter(target))
        res = 100
        for key in t_count.keys():
            res = min(res, s_count.get(key, 0)//t_count[key])
        return res
上一篇 下一篇

猜你喜欢

热点阅读