34 第一个只出现一次的字符
题目描述
在一个字符串中找到第一个只出现一次的字符,并返回它的位置。
示例:
输入: "abaccdeff"
输出: 1 (字符'b'第一次出现在索引1)解题思路
核心思想:使用哈希表统计每个字符出现的次数,然后遍历字符串找第一个只出现一次的字符。
关键步骤:
- 遍历字符串,统计每个字符出现的次数
- 再次遍历字符串,找到第一个出现次数为1的字符
- 返回该字符的位置
时间复杂度:O(n) 空间复杂度:O(1)(字符集有限)或 O(n)
Python 实现
python
def first_not_repeating_char(s):
"""
找到第一个只出现一次的字符的位置
Args:
s: 输入字符串
Returns:
int: 字符的位置,不存在返回-1
"""
if not s:
return -1
# 统计字符出现次数
from collections import Counter
char_count = Counter(s)
# 找第一个只出现一次的字符
for i, char in enumerate(s):
if char_count[char] == 1:
return i
return -1
# 返回字符版本
def first_not_repeating_char_string(s):
"""
返回第一个只出现一次的字符
"""
if not s:
return ""
from collections import Counter
char_count = Counter(s)
for char in s:
if char_count[char] == 1:
return char
return ""
# 测试代码
if __name__ == "__main__":
test_cases = [
"abaccdeff",
"google",
"aabbc",
"",
"aaaa",
]
for s in test_cases:
pos = first_not_repeating_char(s)
char = first_not_repeating_char_string(s)
if pos != -1:
print(f"'{s}' → 位置:{pos}, 字符:'{char}'")
else:
print(f"'{s}' → 位置:{pos}")
# 输出:
# 'abaccdeff' → 位置:1, 字符:'b'
# 'google' → 位置:4, 字符:'l'
# 'aabbc' → 位置:4, 字符:'c'
# '' → 位置:-1
# 'aaaa' → 位置:-1图解
示例: "abaccdeff"
第一次遍历统计:
a: 2次
b: 1次
c: 2次
d: 1次
e: 1次
f: 2次
第二次遍历查找:
i=0, char='a', count=2 → 跳过
i=1, char='b', count=1 → 找到!
返回位置: 1
---
示例: "google"
统计:
g: 2次
o: 2次
l: 1次
e: 1次
查找:
g: 2次 → 跳过
o: 2次 → 跳过
l: 1次 → 找到!
返回位置: 2