用Python语言在pycharm中编写函数,接收一个字符串,返回其中每个字符的最后一次出现,并按每个字符最后一次出现的先后顺序依次存入列表。例如,对于字符串 ' abcda'的处理结果为['b' ,'c', 'd' ,'a']。
时间: 2024-10-27 15:03:22 浏览: 17
要实现这个功能,你可以创建一个名为`last_occurrences`的函数,使用Python的内置`collections`模块中的`deque`(双端队列)来存储每个字符的最后出现位置。这样可以保证插入和删除操作的时间复杂度为O(1)。以下是一个示例实现:
```python
from collections import deque
def last_occurrences(input_string):
char_positions = {char: deque([]) for char in input_string}
# 遍历字符串,更新每个字符的最后出现位置
for index, char in enumerate(input_string):
char_positions[char].append(index)
# 按照最后一次出现的位置降序排列并存储到列表中
result_list = []
for char, positions in sorted(char_positions.items(), key=lambda x: -1]):
result_list.append(char)
return result_list
# 测试函数
input_str = 'abcda'
result = last_occurrences(input_str)
print(result) # 输出: ['b', 'c', 'd', 'a']
```
[^1]
在这个示例中,我们首先创建了一个空的字典`char_positions`,用于存储每个字符及其对应的最后出现位置。然后遍历输入字符串,每次遇到新字符或字符再次出现时,更新其在字典中的位置。最后,按照最后一次出现的位置从高到低排序字符并添加到结果列表中。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231044947.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pptx](https://img-home.csdnimg.cn/images/20241231044947.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)