【每日一题-LC387】字符串第一个唯一字符序列
Given a string, find the first non-repeating character in it and return its index. If it doesn't exist, return -1.
Examples:
s = "leetcode"
return 0.
s = "loveleetcode"
return 2.
Note: You may assume the string contains only lowercase English letters.
[Python3 code]
class Solution: def firstUniqChar(self, s: str) -> int: myMap = {} for i, ch in enumerate(s): if ch in myMap: myMap[ch] = -1 else: myMap[ch] = i for key, value in myMap.items(): if value != -1: return value return -1
复杂度分析
时间复杂度:O(n),其中 n 是字符串 s 的长度。我们需要进行两次遍历。
空间复杂度:O(∣Σ∣),其中 Σ 是字符集,在本题中 s 只包含小写字母,因此 ∣Σ∣≤26。我们需要 O(∣Σ∣) 的空间存储哈希映射。