重排字符形成目标字符串【LC2287】
You are given two 0-indexed strings
s
andtarget
. You can take some letters froms
and rearrange them to form new strings.Return the maximum number of copies of
target
that can be formed by taking letters froms
and rearranging them.
加油加油
-
思路:使用两个哈希表记录两个字符串中字符出现的次数,假设某个字符的在
s
和target
中出现次数分别为 a a a和 b b b,那么该字母可被重排的次数为 ⌊ a b ⌋ \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
- 复杂度