[TOC]
題目
給定一個字符串,找到它的第一個不重複的字符,並返回它的索引。如果不存在,則返回 -1。
案例:
s = "leetcode"
返回 0.
s = "loveleetcode",
返回 2.
注意事項:您可以假定該字符串只包含小寫字母。
來源:力扣(LeetCode) 鏈接:https://leetcode-cn.com/problems/first-unique-character-in-a-string 著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
解答
leetcode解題
import collections
class Solution1(object): # 方法一
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
for a,i in enumerate(s):
aa = s.replace(i,"",1)
if i not in aa:
return a
class Solution2(object): # 方法二
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
index=0
count = collections.Counter(s)
for i in s:
if count[i]==1:
return index
else:
index+=1
return -1