Python给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
时间: 2023-11-24 18:45:40 浏览: 348
查找第一个相同的字符
5星 · 资源好评率100%
给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
方法一:
```python
def first_not_repeating_char(strings):
chars = []
times = []
for s in strings:
if s not in chars:
chars.append(s)
times.append(1)
else:
char_index = chars.index(s)
times[char_index] += 1
for t in times:
if t == 1:
times_index = times.index(t)
return chars[times_index]
return -1
strings = input('请输入长字符串:')
print('结果:', first_not_repeating_char(strings))
```
方法二:
```python
from collections import Counter
def deal_str(s):
counter = Counter(s)
singles = [_c for _c, _i in counter.items() if _i == 1]
idxs = [s.index(_c) for _c in singles]
idx = min(idxs) if idxs else -1
print(f"字符串({s})中的第一个不重复字符的位置是({idx})")
string = "abcab"
deal_str(string)
```
方法三:
```python
def deal_str2(s):
my_dict = {}
idx = -1
for _i, _c in enumerate(s):
if _c not in my_dict:
my_dict[_c] = _i
else:
my_dict[_c] = 9999
idx = min(my_dict.values())
idx = -1 if idx >= 9999 else idx
print(f"字符串({s})中的第一个不重复字符的位置是({idx})")
string = "abcab"
deal_str2(string)
```
阅读全文