给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
案例:
s = "leetcode"
返回 0.
s = "loveleetcode",
返回 2.
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/first-unique-character-in-a-string
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
第一种思路:
先统计所有元素出现频率,然后从左到右线性扫描,发现的第一个出现次数为1的字符,其下标就是答案。
时间复杂度:O(N)
空间复杂度:O(len(set(s)))
class Solution(object):
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
dic = collections.Counter(s)
for i, ch in enumerate(s):
if dic[ch] == 1:
return i
return -1
第二种思路:
如果输出限定在小写字母的范围内:
则可以找每个字母出现的最左下标和最右下标,如果最左下标 == 最右下标,则说明出现次数为1。
时间复杂度:O(N)
空间复杂度:O(1)
class Solution(object):
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
l = len(s)
for item in "abcdefghijklmnopqrstuvwxyz":
a = s.find(item)
b = s.rfind(item)
if a == b and a!= -1:
l = min(l, a)
return l if l<len(s) else -1