--Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.
--给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
s = "leetcode"
返回 0.
s = "loveleetcode",
返回 2.
- Note: You may assume the string contain only lowercase letters.
注意事项:您可以假定该字符串只包含小写字母。
-
SOLUTION1:
通常的想法是,逐个字母出现的次数数,第一个次数 为 1 的返回:
class Solution:
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
d = {}
for i in range(len(s)):
if s[i] not in d:
d[s[i]] = i
else:
d[s[i]] += len(s)
if len(s) and min(d.values()) < len(s) :
return min(d.values())
return -1
而字母的表示,会想到用数字来代替,通常会用py的ord()函数来实现:
ord() 函数是 chr() 函数(对于8位的ASCII字符串)或 unichr() 函数(对于Unicode对象)的配对函数,它以一个字符(长度为1的字符串)作为参数,返回对应的 ASCII 数值,或者 Unicode 数值,如果所给的 Unicode 字符超出了你的 Python 定义范围,则会引发一个 TypeError 的异常。
>>>ord('a')
97
>>> ord('b')
98
>>> ord('c')
99
代码可以看看:
class Solution(object):
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
t = [0]*26
for ai in s:
t[ord(ai)-ord('a')]+=1
for index,ai in enumerate(s):
if t[ord(ai)-ord('a')]==1:
return index
return -1
在这个基础上改进的,就是哈希表:会稍微快一些:
class Solution(object):
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
hash_map = {}
for c in s:
if c not in hash_map:
hash_map[c] = 1
else:
hash_map[c] += 1
for i in range(len(s)):
c = s[i]
if c in hash_map and hash_map[c] == 1:
return i
return -1
-
Sol 2:
看到别人用了下面这个方法,速度提高几乎一半:
class Solution(object):
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
letters='abcdefghijklmnopqrstuvwxyz'
index=[s.index(l) for l in letters if s.find(l) != -1 and s.find(l) == s.rfind(l)]
return min(index) if len(index) > 0 else -1
class Solution(object):
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
return min([s.find(c) for c in 'abcdefghijklmnopqrstuvwxyz' if s.count(c)==1] or [-1])
其中 ,运行最快的是以下这个:
class Solution(object):
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
alphbet = "qwertyuiopasdfghjklzxcvbnm"
minPos = len(s)
for i in range(0, len(alphbet)):
start = s.find(alphbet[i])
if start != -1 and start == s.rfind(alphbet[i]):
minPos = min(minPos, start)
print(minPos)
if minPos == len(s):
return -1
else:
return minPos