重排字符形成目标字符串【LC2287】
You are given two 0-indexed strings
sandtarget. You can take some letters fromsand rearrange them to form new strings.Return the maximum number of copies of
targetthat can be formed by taking letters fromsand rearranging them.
加油加油
-
思路:使用两个哈希表记录两个字符串中字符出现的次数,假设某个字符的在
s和target中出现次数分别为aaa和bbb,那么该字母可被重排的次数为⌊ab⌋\lfloor \frac{a}{b} \rfloor⌊ba⌋,target可以被重排的次数为所有字母可被重排的最小值。 -
实现
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
- 复杂度

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

被折叠的 条评论
为什么被折叠?



