2287. 重排字符形成目標(biāo)字符串
給你兩個下標(biāo)從 0 開始的字符串 s 和 target 勃痴。你可以從 s 取出一些字符并將其重排秋柄,得到若干新的字符串峻堰。
從 s 中取出字符并重新排列挽铁,返回可以形成 target 的 最大 副本數(shù)。
- 1 <= s.length <= 100
- 1 <= target.length <= 10
- s 和 target 由小寫英文字母組成
輸入:s = "ilovecodingonleetcode", target = "code"
輸出:2
解釋:
對于 "code" 的第 1 個副本霜旧,選取下標(biāo)為 4 撩穿、5 、6 和 7 的字符萍倡。
對于 "code" 的第 2 個副本,選取下標(biāo)為 17 辟汰、18 列敲、19 和 20 的字符阱佛。
形成的字符串分別是 "ecod" 和 "code" ,都可以重排為 "code" 戴而。
可以形成最多 2 個 "code" 的副本凑术,所以返回 2 。
- 思路:分別對兩個字符串進行字符做哈希統(tǒng)計所意,然后求每個字符的最小倍數(shù)淮逊,說明是可以構(gòu)成映射關(guān)系的
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:
# 求最小倍數(shù),除數(shù)取整
for k in s_count.keys():
res = min(res, s_count[k]//t_count[k])
return res
- 哈希表的改進:計數(shù)器counter+字典
class Solution:
def rearrangeCharacters(self, s: str, target: str) -> int:
# 字典統(tǒng)計
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