python里在字符串中找出第一个只出现一次的字符的两种方法
时间: 2023-04-04 14:04:49 浏览: 76
可以使用字典来统计每个字符出现的次数,然后再遍历一遍字符串找到第一个出现次数为1的字符。另一种方法是使用Python内置的collections模块中的Counter类来统计每个字符出现的次数,然后再遍历一遍字符串找到第一个出现次数为1的字符。
相关问题
用两种方法,编写一个python程序,能在字符串中找出第一个只出现一次的字符,要求时间复杂度不超过O(n)
方法一:
```python
def find_first_unique_char(s):
char_count = {}
for c in s:
if c in char_count:
char_count[c] += 1
else:
char_count[c] = 1
for c in s:
if char_count[c] == 1:
return c
return None
```
方法二:
```python
def find_first_unique_char(s):
char_count = {}
for c in s:
if c in char_count:
char_count[c] += 1
else:
char_count[c] = 1
for i, c in enumerate(s):
if char_count[c] == 1:
return c
return None
```
这两种方法的时间复杂度都是O(n),第一种方法使用了两次循环,第二种方法使用了一次循环和一次枚举。
python:在字符串中查找指定字符的多个索引方法
可以使用 `find()` 和 `index()` 方法来查找指定字符的索引,但它们只能返回第一个匹配的索引。如果想要查找所有的匹配索引,可以使用列表解析或正则表达式。
1. 使用列表解析:
```python
string = "hello world"
char = "l"
indices = [i for i, c in enumerate(string) if c == char]
print(indices) # 输出 [2, 3, 9]
```
2. 使用正则表达式:
```python
import re
string = "hello world"
char = "l"
indices = [m.start() for m in re.finditer(char, string)]
print(indices) # 输出 [2, 3, 9]
```
这两种方法都可以查找指定字符的所有索引。注意,`index()` 方法在找不到指定字符时会抛出 `ValueError` 异常,而 `find()` 方法会返回 `-1`。因此,如果使用这两种方法,需要对异常和返回值进行判断。