原题
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.
解法
先用字典存储每个字符出现的次数, 然后遍历字符串, 当出现字母次数为1时, 返回当前index.
Time: 2*O(n)
Space: O(1)
代码
class Solution(object):
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
count = collections.Counter(s)
for i, char in enumerate(s):
if count[char] == 1:
return i
return -1
本文深入探讨了一种高效算法,用于在字符串中查找第一个不重复的字符,并详细解释了其实现过程。通过使用字典记录字符出现频率,再遍历字符串定位目标字符,此方法在时间和空间复杂度上表现优异。
315

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



