LeetCode 387 solution
387. First Unique Character in a String
#hash_table
problem
Given a strings
, 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:
1 <= s.length <= 105
s
consists of only lowercase English letters.
python
class Solution:
def firstUniqChar(self, s: str) -> int:
hash_t = {}
for i in s:
hash_t[i] = hash_t.get(i,0) + 1
for idx,j in enumerate(s):
if hash_t[j] == 1:
return idx
return -1
Its not that difficult problem. Just check the frequency of each char in s
with hash table. And if the frequency is 1 -> return it's index, else return -1.
The important point of this code is hash_[t] = hash_t.get(i,0) + 1
this part. No need to conditionally make is there is no pre existence of char in hash table. This is python dict data structure's good point to get.