解法一:扫两遍,第一遍存字典,第二遍遍历字典找到最小索引,代码如下:
class Solution:
def firstUniqChar(self, s: str) -> int:
d = {}
for i, c in enumerate(s):
if c in d:
d[c] = len(s)
else:
d[c] = i
mi = len(s)
for c in d:
if d[c] < mi: mi = d[c]
if mi == len(s): return -1
return mi
解法二:延迟删除
这是一种不错的思路,假如第一个就是我们要的元素,第二遍扫描就没必要进行了,这是我们的核心思想,不扫没必要的地方。做法就是存一个队列,只有首元素凉了,才有必要继续往下删。
from collections import deque
class Solution:
def firstUniqChar(self, s: str) -> int:
q = deque()
d = {}
for i, c in enumerate(s):
if c in d:
d[c] = len(s)
while len(q) and d[q[0]] == len(s):
q.popleft()
else:
d[c] = i
q.append(c)
if len(q) == 0: return -1
return d[q[0]]
速度有没有变快不好说,但思路是个不错的思路。但在一些情况下,确实能提升检索速度。