给定一个包含较低字母的字符串,我们最多需要从该字符串中删除一个字符,这样每个不同字符在该字符串中的频率就变得相同。
null
例如:
Input : str = “xyyz” Output : Yes We can remove character ’y’ from above string to make the frequency of each character same. Input : str = “xyyzz” Output : Yes We can remove character ‘x’ from above string to make the frequency of each character same. Input : str = “xxxxyyzz” Output : No It is not possible to make frequency of each character same just by removing at most one character from above string.
此问题已有解决方案,请参考 检查所有字符的频率是否可以通过一次删除而变得相同 链接我们将用Python快速解决这个问题。方法很简单,
- 我们需要计算字符串中每个字母的频率,为此我们将使用 计数器(输入) 方法返回一个字典,其中字符作为键,它们各自的频率作为值。
- 现在提取每个字符的频率列表,并输入这些值 Set() python中的数据结构。
- 因为集合包含唯一的值,所以如果集合的大小为1,这意味着所有字符的频率都相同,如果集合的大小为2,则检查第一个元素的值是否为1(如果为1,则我们可以通过删除最多一个字符来获得相同的频率,否则是不可能的)。
# Function to Check if frequency of all characters
# can become same by one removal
from
collections
import
Counter
def
allSame(
input
):
# calculate frequency of each character
# and convert string into dictionary
dict
=
Counter(
input
)
# now get list of all values and push it
# in set
same
=
list
(
set
(
dict
.values()))
if
len
(same)>
2
:
print
(
'No'
)
elif
len
(same)
=
=
2
and
same[
1
]
-
same[
0
]>
1
:
print
(
'No'
)
else
:
print
(
'Yes'
)
# now check if frequency of all characters
# can become same
# Driver program
if
__name__
=
=
"__main__"
:
input
=
'xxxyyzzt'
allSame(
input
)
输出:
No
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END