LeetCode_387. 字符串中的第一个唯一字符
写在前面
题目
示例 1:
输入: s = "leetcode"
输出: 0
示例 2:
输入: s = "loveleetcode"
输出: 2
示例 3:
输入: s = "aabb"
输出: -1
提示:
1 <= s.length <= 105
s 只包含小写字母
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/first-unique-character-in-a-string
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路1:
class Solution:
def firstUniqChar(self, s: str) -> int:
for index,_ in enumerate(s): #遍历字符串获取索引
if s.count(_)==1: #如果计数为1
return index #则返回
else:
return -1 #没找到计数为1的,就返回-1
-
方法1的解决效果,写的时候就能想到,耗时比较慢,因为每次获取到一个字符都要从头去遍历一遍。
思路2:hash表
-
count的问题可以通过hash表来规避
-
得到一个字符的时候设置其次数为1,第二次遇到就+1,依次类推,最终去找value为1的,没有就返回-1
class Solution:
def firstUniqChar(self, s: str) -> int:
hash_s = {}
for _ in s:
hash_s[_] = hash_s[_]+1 if _ in hash_s else 1
for k,v in hash_s.items():
if v==1:
return s.index(k)
else:
return -1
思路3:
-
其实hash表那部分代码就是python的一些标准库
s = 'hello'
from collections import Counter
counter = Counter(s)
print(dict(counter)) #{'h': 1, 'e': 1, 'l': 2, 'o': 1} -
修改上述代码
class Solution:
def firstUniqChar(self, s: str) -> int:
from collections import Counter
hash_s = dict(Counter(s))
for k,v in hash_s.items():
if v==1:
return s.index(k)
else:
return -1 -

浙公网安备 33010602011771号