python中如何给定一个字符串,找到它的第一个不重复的字符,输出它的索引。如果不存在这种字符或空串,则返回 -1。
时间: 2024-02-12 12:06:31 浏览: 38
可以使用Python中的字典来解决这个问题,具体实现如下:
```python
def find_first_unique_char(s):
char_count = {}
# 统计每个字符出现的次数
for char in s:
if char in char_count:
char_count[char] += 1
else:
char_count[char] = 1
# 找到第一个出现次数为1的字符
for i, char in enumerate(s):
if char_count[char] == 1:
return i
return -1 # 如果不存在这种字符或空串,则返回 -1
# 测试
print(find_first_unique_char("leetcode")) # 应输出 0
print(find_first_unique_char("loveleetcode")) # 应输出 2
print(find_first_unique_char("aabbcc")) # 应输出 -1
```
在上面的代码中,首先用一个字典`char_count`来统计每个字符在字符串`s`中出现的次数。然后再遍历一遍字符串`s`,找到第一个出现次数为1的字符并返回它的索引。如果不存在这种字符或空串,则返回 -1。
相关问题
Python给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -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)
```
写出代码:给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
以下是使用 Python 3 实现的代码:
```python
def firstUniqChar(s: str) -> int:
char_count = {}
for char in s:
if char in char_count:
char_count[char] += 1
else:
char_count[char] = 1
for idx, char in enumerate(s):
if char_count[char] == 1:
return idx
return -1
```
我们首先构建一个字典 `char_count`,用于存储每个字符在字符串中出现的次数。然后遍历一遍字符串,统计每个字符出现的次数。接着再次遍历字符串,找到第一个出现次数为 1 的字符并返回它的索引。如果没有找到,则返回 -1。