Table of Contents
一、中文版
给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
示例:
s = "leetcode" 返回 0 s = "loveleetcode" 返回 2
提示:你可以假定该字符串只包含小写字母。
二、英文版
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 English letters.
三、My answer
自己写的代码比较繁琐,LeetCode 官方题解非常简洁,记录在此,提醒自己多看。
class Solution:
def firstUniqChar(self, s: str) -> int:
# build hash map : character and how often it appears
count = collections.Counter(s)
# find the index
for idx, ch in enumerate(s):
if count[ch] == 1:
return idx
return -1
# 作者:LeetCode
# 链接:https://leetcode-cn.com/problems/first-unique-character-in-a-string/solution/zi-fu-chuan-zhong-de-di-yi-ge-wei-yi-zi-fu-by-leet/
# 来源:力扣(LeetCode)
# 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
四、解题报告
数据结构:collections.Counter(s)
算法:遍历
实现:从前往后遍历。这种找第一个 XXX 的问题,可以考虑从前往后遍历,遇到符合题意的第一个,就是题解。