python 实现两种解决方法

第一种方法

遍历整个字符串,利用字典缓存是否已经出现字符。如果出现放入字典,在加入之前需要判断当前字符是否出现如果出现如果字符串不是唯一直接返回False。 遍历之后没有中断说明是唯一字符串。

class Solution:
    def isUnique(self , str: str) -> bool:
        # write code here
        map = {}
        for c in str:
          if map.get(c, False): return False
          map.setdefault(c, True)
        return True

第二种方法

通过Counter 类统计字符串。然后取出统计出现最多的字符一项。如果最多一项出现的次数为一说明是唯一的。反之不是

from collections import Counter
def isUnique(str: str) -> bool:
  count = Counter(str)
  # 获取出现最多的字符一项
  return count.most_common(1)[0][1] == 1