题目:
面试题 01.01. 判定字符是否唯一.
实现一个算法,确定一个字符串 s 的所有字符是否全都不同。
链接:https://leetcode-cn.com/problems/is-unique-lcci/
示例:
输入: s = “leetcode”
输出: false
输入: s = “abc”
输出: true
限制:
0 <= len(s) <= 100
如果你不使用额外的数据结构,会很加分。
思路:
借助python中的字典数据类型,将查询的时间复杂度降为O(1)。遍历字符串中的字符,判断其是否在字典中,若不在则加入,若存在则直接返回False。最终遍历完所有字符,返回True。
没想到不使用额外数据结构的方法。
代码:
class Solution:
def isUnique(self, astr: str) -> bool:
dict_ = {}
for a in astr:
if a not in dict_:
dict_[a] = 1
else:
return False
return True
时间复杂度O(n),空间复杂度O(n).