给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
示例:
s = “leetcode”
返回 0
s = “loveleetcode”
返回 2
提示:你可以假定该字符串只包含小写字母。
解法一:使用哈希表存储频数
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
解法二:使用哈希表存储索引
class Solution:
def firstUniqChar(self, s: str) -> int:
position = dict()
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
解法三:队列
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]
解法四:python的find和rfind
class Solution:
def firstUniqChar(self, s: str) -> int:
for x in s:
if s.find(x) == s.rfind(x):
return s.find(x)
return -1
python字符串遍历方法:https://www.cnblogs.com/qa-freeroad/p/14100757.html
菜鸟教程:https://www.runoob.com/python/att-string-rfind.html
find() 是从字符串左边开始查询子字符串匹配到的第一个索引;
rfind()是从字符串右边开始查询字符串匹配到的第一个索引。返回字符串最后一次出现的位置,如果没有匹配项则返回-1。
力扣 (LeetCode)链接:https://leetcode-cn.com/leetbook/read/top-interview-questions-easy/xn5z8r/