在一个长为n的字符串中找到第一个只出现一次的字符,并输出它的位置,如果没有则输出-1(需要区分大小写)n的范围是0~10000,并且字符串只有字母组成
时间: 2024-04-15 09:32:10 浏览: 25
如果字符串长度为n,且只包含字母,我们可以使用一个长度为26的数组来存储每个字母出现的次数。遍历字符串,统计每个字母出现的次数,然后再次遍历字符串,找到第一个出现次数为1的字母,并输出它的位置。
代码如下:
```python
def find_first_unique_char(s):
char_count = [0] * 26
char_index = [-1] * 26
for i, c in enumerate(s):
index = ord(c) - ord('a')
char_count[index] += 1
char_index[index] = i
min_index = float('inf')
for i, c in enumerate(s):
index = ord(c) - ord('a')
if char_count[index] == 1 and char_index[index] < min_index:
min_index = char_index[index]
if min_index == float('inf'):
return -1
return min_index
```
调用示例:
```python
s = "abaccdeff"
print(find_first_unique_char(s)) # 输出 1
```
如果字符串中没有只出现一次的字符,则会返回-1。