题目

实现一个算法,确定一个字符串 s 的所有字符是否完全都不同。
image.png

思路

两种方法

  1. 使用set去重之后比较去重后的长度和原始长度
  2. 使用集合(无序不重复 )保存遍历过的元素,一旦有重复就返回False。
    1. class Solution:
    2. def isUnique(self, astr: str) -> bool:
    3. return len(set(astr)) == len(astr)
    1. class Solution:
    2. def isUnique(self, astr: str) -> bool:
    3. no_repeat = set()
    4. for ch in astr:
    5. if ch in no_repeat:
    6. return False
    7. else:
    8. no_repeat.add(ch)
    9. return True