字符串中的第一个唯一字符
给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
示例:
s = "leetcode" 返回 0 s = "loveleetcode" 返回 2
提示:你可以假定该字符串只包含小写字母。
class·Solution:
····def·firstUniqChar(self,·s:·str)·->·int:
········dict={}
········for·i·in·s:
············if·dict.get(i):
················dict[i]·=·dict.get(i)+1
············else:
················dict[i]·=·1
········for·j·in·s:
············if·dict[j]==1:
················return·t
········return·-1
········t·=·0
············t·+=·1
查看题解
测试用例执行结果提交结果
执行结果:
通过
显示详情
执行用时:180 ms, 在所有 Python3 提交中击败了21.72%的用户
内存消耗:14.9 MB, 在所有 Python3 提交中击败了75.30%的用户
炫耀一下:
控制台执行代码提交
if
class Solution:
def firstUniqChar(self, s: str) -> int:
dict={}
for i in s:
if dict.get(i):
dict[i] = dict.get(i)+1
else:
dict[i] = 1
t = 0
for j in s:
if dict[j]==1:
return t
t += 1
return -1