给定一个字符串 s ,找到 它的第一个不重复的字符,并返回它的索引 。如果不存在,则返回 -1 。
示例 1:
输入: s = “leetcode”
输出: 0
示例 2:
输入: s = “loveleetcode”
输出: 2
示例 3:
输入: s = “aabb”
输出: -1
提示:
1 <= s.length <= 105
s 只包含小写字母
class Solution:
def firstUniqChar(self, s: str) -> int:
dic = {}
# 记录字符出现次数
for c in s:
dic[c] = dic[c] + 1 if c in dic else 1
# 过滤出现次数不为一的字符
unique_chars = [k for k, v in filter(lambda kvp: kvp[1] == 1, dic.items())]
# 遍历目标字符串,返回首个出现在unique_chars中的字符的索引
for i, c in enumerate(s):
if c in unique_chars:
return i
return -1
更简洁的写法
class Solution:
def firstUniqChar(self, s: str) -> int:
frequency = collections.Counter(s)
for i, ch in enumerate(s):
if frequency[ch] == 1:
return i
return -1
时间复杂度:O(n)
空间复杂度:O(26)
class Solution:
def firstUniqChar(self, s: str) -> int:
position = {}
n = len(s)
for i, ch in enumerate(s):
if ch in position:
position[ch] = -1
else:
position[ch] = i
first = n
for pos in position.values():
if pos != -1 and pos < first:
first = pos
if first == n:
first = -1
return first
时间复杂度:O(n)
空间复杂度:O(26)
class Solution:
def firstUniqChar(self, s: str) -> int:
position = dict()
q = collections.deque()
n = len(s)
for i, ch in enumerate(s):
if ch not in position:
position[ch] = i
q.append((s[i], i))
else:
position[ch] = -1
while q and position[q[0][0]] == -1:
q.popleft()
return -1 if not q else q[0][1]
时间复杂度:O(n)
空间复杂度:O(26)