输入字符串,输出字符串中出现次数最多的字母及其出现次数,如果有多个字母出现次数一样,按字符从小到大顺序输出字母及其出现次数
时间: 2023-06-20 07:05:08 浏览: 724
Python实现计算字符串中出现次数最多的字符示例
可以使用哈希表来记录每个字母出现的次数,然后遍历哈希表找到出现次数最多的字母及其出现次数。如果有多个字母出现次数一样,可以将哈希表按键值(即字母)从小到大排序后输出。
以下是 Python 代码实现:
```python
def max_occurrence(s):
# 构建哈希表记录每个字母出现的次数
count = {}
for c in s:
count[c] = count.get(c, 0) + 1
# 找到出现次数最多的字母及其出现次数
max_count = 0
max_chars = []
for c in count:
if count[c] > max_count:
max_count = count[c]
max_chars = [c]
elif count[c] == max_count:
max_chars.append(c)
# 对出现次数一样的字母按字符从小到大排序
max_chars.sort()
# 返回结果
return max_chars[0], max_count
```
测试:
```python
s = 'hello world'
print(max_occurrence(s)) # ('l', 3)
s = 'abcbcdcde'
print(max_occurrence(s)) # ('c', 3)
```
阅读全文