Reckon NO.384 first unique character in string (hash table; use of Counter())

topic link

insert image description here

Method 1: Use a hash table to store the frequency, Counter() method

Please add image description

import collections
class Solution:
    def firstUniqChar(self, s: str) -> int:
        frequency = collections.Counter(s) # 获取频数字典
        for i,x in enumerate(s):
            if frequency[x] ==1:  # 如果是不重复字符
                return i # 返回该字符下标
        return -1 # 没有则返回-1

Method 2: Use a hash table to store the frequency instead of Counter()

Please add image description

class Solution:
    def firstUniqChar(self, s: str) -> int:
        position = {}
        n = len(s)
        # 创建位置字典:键:字符,值:唯一字符首次出现的索引,i:字符首次出现的位置,-1:字符多次出现
        for i,ch in enumerate(s):
            if ch in position:  # 使用 in 判断字符在不在字典的键中 
                position[ch] = -1 # 在,字符出现多次,改值为-1
            else:
                position[ch] = i # 不在,字符首次出现,添加该字符,及位置i
        min_first = n #最小的首次出现的位置
        # 遍历字典的值,更新min_first
        for pos in position.values():
            if pos != -1:
                min_first = min(pos,min_first)
        if min_first == n: # 最小首次出现位置未更新
            min_first = -1
        return min_first

Guess you like

Origin blog.csdn.net/qq_33489955/article/details/124268438