【每日算法】宝,你今天练算法了吗?

215 阅读1分钟

题目:

实现一个算法,确定一个字符串 s 的所有字符是否全都不同(Python实现)

s = 'leetcode'
false

s = 'abc'
true

第一种解题思路:将不重复的元素放到列表中,判断列表长度和字符串长度

def isUnique(s):
    li = []
    for i in s:
        if i not in li:
            li.append(i)

    if len(li) != len(s):
        return False
    else:
        return True

第二种解题思路:将字符串用内置函数 set() 转换为集合,此时集合会自动排除重复项。

def isUnique(s):
    ns = set(s)
    if len(ns) != len(s):
        return False
    else:
        return True