原题
Given a string, find the first non-repeating character in it and return it’s index. If it doesn’t exist, return -1.
Examples:
s = “leetcode”
return 0.
s = “loveleetcode”,
return 2.
Note: You may assume the string contain only lowercase letters.
解法
使用字典计数, 然后遍历s, 返回第一个计数为1的index.
Time: O(n)
Space: O(1)
代码
class Solution(object):
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
d = collections.Counter(s)
for i, ch in enumerate(s):
if d[ch] == 1:
return i
return -1
本文介绍了一种高效算法,用于查找给定字符串中的第一个不重复字符,并返回其索引位置。通过使用Python的collections.Counter进行字符计数,然后遍历字符串来实现O(n)时间复杂度和O(1)空间复杂度。
314

被折叠的 条评论
为什么被折叠?



