假设我们有一个小写的字符串s。删除一个字符后,我们必须检查所有字符的频率是否相同。
因此,如果输入类似于s =“ abbc”,则输出将为True,因为我们可以删除一个b以获得字符串“ abc”,其中每个元素的频率为1。
让我们看下面的实现以更好地理解-
from collections import defaultdict def allSame(occurrence): counts = list(occurrence.values()) return all(element == counts[0] for element in counts) def solve(s): occurrence = defaultdict(int) for char in s: occurrence[char] += 1 if allSame(occurrence): return True for char in s: occurrence[char] -= 1 if allSame(occurrence): return True occurrence[char] += 1 return False s = "abbc" print(solve(s))
"abbc"输出结果
True