我明明 Filter 題目時有 apply tag "Stack",結果做一做發現今天的題目根本不需要 Stack...
https://leetcode.com/problems/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
Example 2:
Input: s = "loveleetcode"
Output: 2
Example 3:
Input: s = "aabb"
Output: -1
Constraints:
https://realpython.com/python-counter/
Python 可以用 collections 裡面的 Counter 函式來計算物件出現的次數,因為這個函式裡面是用 C 語言實作,所以會比自己用 dict 計算次數來得快.
>>> from collections import Counter
>>> # Use a string as an argument
>>> Counter("mississippi")
Counter({'i': 4, 's': 4, 'p': 2, 'm': 1})
Python
from collections import Counter
class Solution:
def firstUniqChar(self, s: str) -> int:
count = Counter(s)
indexes = [s.index(letter) for letter in count if count[letter] == 1]
return min(indexes) if indexes else -1
Go 沒有 Counter 函式可以用.必須用 HashMap 來計算次數.
func firstUniqChar(s string) int {
count := map[rune]int{}
for _, letter := range s {
count[letter]++
}
for index, letter := range s {
if count[letter] == 1 {
return index
}
}
return -1
}