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.
思路:一开始的想法就是用count()方法遍历,找到第一个count为1的字母,如下面这种方法,不过这样会超时。
class Solution:
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
for i,char in enumerate(s):
if s.count(char)==1:
return i
return -1
然后想到利用collections的Counter()方法,先统计个数,再对个数为1的进行位置比较,返回第一个个数为1字母的位置。
from collections import Counter
class Solution:
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
min = float('inf')
dic = Counter(s)
for key,val in dic.items():
if val==1:
if min>s.index(key):
min = s.index(key)
if min!=float('inf'):
return min
return -1
看了discuss,有更快的方法,不过要事先设好输入的letters。
class Solution:
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
letters='abcdefghijklmnopqrstuvwxyz'
index=[s.index(l) for l in letters if s.count(l) == 1]
return min(index) if len(index) > 0 else -1

本文探讨了在字符串中查找第一个不重复字符及其索引的有效算法。通过使用Python的Counter方法,文章提供了一种比简单遍历更高效的方法。此外,还介绍了一个更快的解决方案,该方案针对预定义的字母表进行了优化。
507

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



