时间:2020-9-2
题目地址:https://leetcode-cn.com/problems/first-unique-character-in-a-string/
题目难度:Easy
题目描述:
给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
示例:
s = "leetcode"
返回 0
s = "loveleetcode"
返回 2
思路1:用哈希,一看到次数,毫不犹豫用哈希
代码段1:通过
class Solution:
def firstUniqChar(self, s: str) -> int:
dict = {}
for i, ss in enumerate(s):
if ss in dict:
dict[ss] += 1
else:
dict[ss] = 1
for (j, ss) in dict.items():
if ss == 1:
return s.index(j)
return -1
总结:
- 其实自己的写法有很多问题,对数据结构及方法用的很混乱,看下正确优雅的写法
class Solution:
def firstUniqChar(self, s: str) -> int:
dict = {}
for i in s:
dict[i] = dict.get(i, 0) + 1
for j in dict.keys():
if dict[j] == 1:
return s.index(j)
return -1
思路2:用哈希,lambda, filter用起来
代码段2:通过
class Solution:
def firstUniqChar(self, s: str) -> int:
dict = {}
for i in s:
dict[i] = dict.get(i, 0) + 1
unique_chars = [k for k, v in filter(lambda kvp: kvp[1] == 1, dict.items())]
for i, c in enumerate(s):
if c in unique_chars:
return i
return -1
总结:
- 这块不咋熟,多写写吧
思路3:字典+集合,使用内置的set() 及 str.count()
代码段3:通过
class Solution:
def firstUniqChar(self, s: str) -> int:
dict = {c: s.count(c) for c in set(s)}
for i, c in enumerate(s):
if dict[c] == 1:
return i
return -1
总结:
- 这一道简单题,太考验数据结构基础了
思路4:时间很短的一个改进算法
代码段4:通过
class Solution:
def firstUniqChar(self, s: str) -> int:
# 先假设最小索引为最后的字符索引
min_unique_char_index = len(s)
# 已知字符串由小写字母构成,则遍历a-z
for c in "abcdefghijklmnopqrstuvwxyz":
i = s.find(c)
# 分别从目标的字符串头和字符串尾查找对应字母的索引;如果两索引相等,则说明是单一字符
if i != -1 and i == s.rfind(c):
# 更新最新的最小索引
min_unique_char_index = min(min_unique_char_index, i)
# 如果返回值不为最后字符的索引,则返回最小索引值
# 否则,根据题意,返回-1
return min_unique_char_index if min_unique_char_index != len(s) else -1
总结:
- 挺厉害的