letcode 第三题 判定字符是否唯一

实现一个算法,确定一个字符串 s 的所有字符是否全都不同。

示例 1:

输入: s = "leetcode"
输出: false 

示例 2:

输入: s = "abc"
输出: true

 

方法一:

使用一个简单的count()函数,统计每一个单词的数字,再来判断。(Set也同理,字典也行,列表也行)

class Solution:
    def isUnique(self, astr: str) -> bool:
        for i in astr:
            if astr.count(i)>1:
                return False
        return True


字典使用的是

def isUnique(self, astr: str) -> bool:
  adict={}
  for value in astr:
    if value in adict.keys():
      return False
    else:
      adict[value]=0
  return True

 



class Solution:
def isUnique(self, astr: str) -> bool:
return len(astr)== len(set(astr))

方法二:

使用位运算。

我们可以使用一个int类型的变量(下文用mark表示)来代替长度为26的bool数组。假设这个变量占26个bit(在多数语言中,这个值一般不止26)。

那么我们可以把它看成000...00(26个0),这26个bit对应着26个字符,对于一个字符c,检查对应下标的bit值即可判断是否重复。

学到了。

class Solution:
  def isUnique(self, astr: str) -> bool:
    mark = 0
    for char in astr:
      move_bit = ord(char) - ord('a')
      if (mark & (1 << move_bit)) != 0:
        return False
      else:
        mark |= (1 << move_bit)
    return True。

作者:zhen-zhu-hao-hao-chi
链接:https://leetcode-cn.com/problems/is-unique-lcci/solution/wei-yun-suan-fang-fa-si-lu-jie-shao-by-zhen-zhu-ha/
来源:力扣(LeetCode)

 

posted @ 2020-05-07 12:35  我和姚明一样高  阅读(216)  评论(0编辑  收藏  举报