题目:字符串中的第一个唯一字符
给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
案例:
s = "leetcode",返回 0.
s = "loveleetcode", 返回 2.
注意事项:您可以假定该字符串只包含小写字母。
-------------------------------------------------------------------------------------------------------------
解法1:字典统计字符频率
class Solution(object):
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
dic = {}
for str in s:
if str not in dic.keys():
dic[str] = 1
else:
dic[str] += 1
for i in range(len(s)):
if dic[s[i]] == 1:
return i
return -1
解法2:通过collections中的Counter()方法
count() 方法用于统计字符串里某个字符出现的次数。可选参数为在字符串搜索的开始与结束位置。
count()方法语法:str.count(sub, start= 0,end=len(string))
class Solution(object):
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
import collections
dic = collections.Counter(s)
for i in range(len(s)):
if dic[s[i]] == 1:
return i
return -1
解法3:解法2的优雅版(利用了都是小写字母的条件)
class Solution(object):
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
lowercase = 'abcdefghijklmnopqrstuvwxyz'
res = [s.index(label) for label in lowercase if s.count(label) == 1]
if len(res):
return min(res)
return -1
解法4:网友提供了一个妙法,切片。虽然效率不高,但很有意思。
class Solution(object):
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
for i in range(len(s)):
str = s[:i] + s[i+1:]
if s[i] not in str:
return i
return -1
参考:
https://www.runoob.com/python/att-string-count.html