給定一個(gè)字符串string,如果字符串所有字符唯一則返回True,否則返回False
列子:
None -> False
"" -> True
"hello" -> False
"world" -> True
假設(shè)字符串都是ASCII字符組成
解法一:
def has_unique_chars(string):
if string is None:
print("string is None")
return False
return len(set(string)) == len(string)
解法二:
def another(string):
char_set = set()
if string is None:
return False
for char in string:
if char in char_set:
return False
else:
char_set.add(char)
return True
測(cè)試
str = ''
print(has_unique_chars(str))