天天看点

字符串篇(python)—如何判断字符串是否包含重复字符

如何判断字符串是否包含重复字符

一种以时间换空间的方法

"""
判断一个字符串是否重复字符 例如:good就包含重复字符 而abc就不包含重复字符串
"""
def isDup(strs):
    lens = len(strs)
    i = 0
    while i < lens:
        j = i + 1
        while j < lens:
            if list(strs)[j] == list(strs)[i]:
                return True
            j += 1
        i += 1
    return False


if __name__ == '__main__':
    strs = 'abcdefghijk'
    res = isDup(strs)
    print(res)
           

这是比较简单的题目,上面的实现方法时间复杂度是O(n**2),如何才能降低时间复杂度呢?思考一下。

字符串篇(python)—如何判断字符串是否包含重复字符