'''
总体结题思路:
将字母转化为数字数组储存,然后遍历数字数组,每次将数组里面有值的数-1,
然后在-1之后的新数组里面遍历剩下的元素是否相同
'''
class Solution:
def equalFrequency(self, word: str) -> bool:
ans = [0] * 26 # 将字母转化为数字储存,ord是将字母转化为对应的asc码
for s in word:
ans[ord(s) - ord('a')] += 1
m = [] # m用来返回这么多次的总结果,有值说明可行
# 遍历原始统计的数组
for i in range(len(ans)):
# 如果数组值为0,跳过
if ans[i] == 0:
continue
# 不为0就将其删除一个
ans[i] -= 1
# res用来保存剩下不为0的数组元素,如果里面元素都相同说明是True
res = []
# 遍历删除了一个字母之后的新数组
for j in range(len(ans)):
if ans[j] == 0:
continue
# 如果里面元素不为0,就将其存储到res里
res.append(ans[j])
# res存在的话就判断里面元素是否全是相同的值,不存在就直接返回1
if res:
num = [res[0]] * len(res)
if res == num:
m.append(1)
else:
m.append(1) # res不存在的情况只能是只有一个字符,所以返回1
# 别忘了把删除的字符加上去,重新开始下一轮的遍历
ans[i] += 1
return bool(m)
s = Solution()
print(s.equalFrequency("aazz"))
2423. 删除字符使频率相同---详细解题思路
猜你喜欢
转载自blog.csdn.net/m0_55780358/article/details/130909873
今日推荐
周排行