387. First Unique Character in a String
题目
Given a string s
, find the first non-repeating character in it and return its index. If it does not exist, return -1
.
Example 1:
Input: s = "leetcode"
Output: 0
Explanation:
The character 'l'
at index 0 is the first character that does not occur at any other index.
Example 2:
Input: s = "loveleetcode"
Output: 2
Example 3:
Input: s = "aabb"
Output: -1
Constraints:
1 <= s.length <= 105
s
consists of only lowercase English letters.
Related Topics
思路
解法
py
# leetcode submit region begin(Prohibit modification and deletion)
from collections import Counter, defaultdict
class Solution:
def firstUniqChar(self, s: str) -> int:
locations = {}
dict = defaultdict(int)
for index, value in enumerate(s):
locations[value] = index
dict[value] += 1
for key, value in dict.items():
if value == 1:
return locations[key]
return -1
# leetcode submit region end(Prohibit modification and deletion)
复杂度分析
- 时间复杂度 O(N)
- 遍历 S 所需要的时间 len(s)
- 空间复杂度 O(N)
- 创建 location hashmap 空间为 N = len(s)