实现一个算法,确定一个字符串 s 的所有字符是否全都不同。
示例 1:
输入: s = "leetcode"
输出: false
示例 2:
输入: s = "abc"
输出: true
限制:
0 <= len(s) <= 100
如果你不使用额外的数据结构,会很加分。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/is-unique-lcci
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路1
内置Counter,判断字典值中全1的值个数是否与字典长度相符
class Solution(object):
def isUnique(self, astr):
"""
:type astr: str
:rtype: bool
"""
res=Counter(astr)
return len(res)==sum(res.values())
执行结果:
通过
显示详情
执行用时:8 ms, 在所有 Python 提交中击败了98.78%的用户
内存消耗:12.9 MB, 在所有 Python 提交中击败了100.00%的用户
思路2
比较字符串长度和字符串加入集合后的长度是否相符
class Solution(object):
def isUnique(self, astr):
"""
:type astr: str
:rtype: bool
"""
return len(astr)==len(set(astr))
执行结果:
通过
显示详情
执行用时:24 ms, 在所有 Python 提交中击败了33.79%的用户
内存消耗:12.6 MB, 在所有 Python 提交中击败了100.00%的用户