【每日一题Day86】LC2287 重排字符形成目标字符串 | 哈希表

给定两个字符串s和target,文章讲述了如何通过计算每个字符在s和target中出现的次数,利用最小值确定能重排的最大target副本数。算法使用两个哈希表存储计数,然后遍历找到限制因素,最终得到时间复杂度为O(n+m+C)、空间复杂度为O(C)的解决方案。
摘要由CSDN通过智能技术生成

重排字符形成目标字符串【LC2287】

You are given two 0-indexed strings s and target. You can take some letters from s and rearrange them to form new strings.

Return the maximum number of copies of target that can be formed by taking letters from s and rearranging them.

加油加油

  • 思路:使用两个哈希表记录两个字符串中字符出现的次数,假设某个字符的在starget中出现次数分别为 a a a b b b,那么该字母可被重排的次数为 ⌊ a b ⌋ \lfloor \frac{a}{b} \rfloor batarget可以被重排的次数为所有字母可被重排的最小值。

  • 实现

    class Solution {
        public int rearrangeCharacters(String s, String target) {
            int[] sCount = new int[26];
            int[] tCount = new int[26];
            for (char c : s.toCharArray()){
                sCount[c - 'a']++;
            }
            for (char c : target.toCharArray()){
                tCount[c - 'a']++;
            }
            int res = Integer.MAX_VALUE;
            for (int i = 0; i < 26; i++){
                if (tCount[i] != 0){
                    res = Math.min(res, sCount[i] / tCount[i]);                
                }
            }
            return res;
    
        }
    }
    
    • 复杂度
      • 时间复杂度: O ( n + m + C ) O(n+m+C) O(n+m+C),n、m为字符串长度
      • 空间复杂度: O ( C ) O(C) O(C),C为字符集大小,本题中为26
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值