解法一:
python,列表存储后判断字符是否在列表中
def isUniqueOne(astr: str) -> bool:
strlist = []
for s in astr:
if s not in strlist:
strlist.append(s)
else:
return False
return True
解法二:同一类似,字典存储后判断字符是否在字典中
def isUniqueOne(astr: str) -> bool:
ans = dict()
for s in astr:
if s not in ans:
ans[s]=1
else:
return False
return True
解法三:利用set集合元素不重复
def isUniqueTwo(astr: str) -> bool:
if len(astr) == len(set(astr)):
return True
else:
return False
解法四:python3的 ord函数,返回值是对应的十进制整数,如果有相同的字符串存在,if 里面的条件就不存在了,if里面的值已经被修改为1了,所以就会返回False,个人感觉复杂了,当然,前提是字符串必须只有26字母才行,不然要改
def isUniqueThree(astr: str) -> bool:
hash_char = [0 for i in range(26)]
for char in astr:
if hash_char[ord(char) - 97] == 0:
hash_char[ord(char) - 97] = 1
else:
return False
return True
解法五:使用count()函数,直接判断
def isUniqueThree(astr: str) -> bool:
for i in astr:
if astr.count(i) > 1:
return False
return True
解法六:同一二,输入字符串,判断是否有重复的字符-->剔除字符串中所有重复的字符-->对字符串与原字符串做比较-->没有变化,True;有变化,False
def isUniqueThree(astr: str) -> bool:
nastr = str()
for i in astr:
if i not in nastr:
nastr +=i
return nastr ==astr
解法七:使用循环遍历,如果字符串的索引位置不相等但是值相等,则证明存在重复的字符串
def isUniqueThree(astr: str) -> bool:
for s in range(len(astr)):
for n in range(len(astr)):
if s != n and astr[s] == astr[n]:
return False
return True