python中,用O(n)的时间复杂度,在一个字符串里找到所有包含的字符的第一次出现的位置,并且返回每个位置上的字符在字符串中曾经出现的次数
时间: 2024-05-05 18:19:50 浏览: 129
可以使用一个哈希表来记录每个字符出现的位置和出现的次数,然后遍历字符串,对于每个字符,如果它在哈希表中没有出现过,就将它的位置和出现次数记录到哈希表中;如果它已经出现过,就只需要更新它的出现次数。最后,遍历哈希表,将每个字符在字符串中出现的次数返回即可。
以下是示例代码:
```python
def find_char_positions(s):
char_positions = {}
for i, c in enumerate(s):
if c not in char_positions:
char_positions[c] = (i, 1)
else:
char_positions[c] = (char_positions[c][0], char_positions[c][1]+1)
return char_positions
s = "abcaabbccd"
char_positions = find_char_positions(s)
for c in char_positions:
print("Character", c, "first appears at position", char_positions[c][0], "with a count of", char_positions[c][1])
```
输出:
```
Character a first appears at position 0 with a count of 2
Character b first appears at position 1 with a count of 2
Character c first appears at position 2 with a count of 2
Character d first appears at position 8 with a count of 1
```
阅读全文