package
Version:
v0.0.0-...-b071cee
Opens a new window with list of versions in this module.
Published: Aug 9, 2023
License: GPL-3.0
Opens a new window with license information.
Imports: 0
Opens a new window with list of imports.
Imported by: 0
Opens a new window with list of known importers.
README
¶
判定字符是否唯一
1. 题目描述
实现一个算法,确定一个字符串 s 的所有字符是否全都不同。
2. 示例
示例1
输入: s = "leetcode"
输出: false
示例2
输入: s = "abc"
输出: true
提示:
0 <= len(s) <= 100
如果你不使用额外的数据结构,会很加分。
3. 解题
- 暴力匹配法
- 收集法
依次将每一个字符收集到map中,若map中已有该字符,说明存在相同字符
- 排序法
将字符排序,再对比相邻字符
- 位运算
原理:
000100 && 000100 = 1 > 0
为每一个字符定义一个标记:其ascii码与'a'的距离(distance(dt))
这个标记可以像这样记录在一个二进制数bin上:
如果dt为'c'-'a' = 2,那么 bin | (1 << 2), 即将bin的从右到左第2位设置为1, 代表距离'a'长度为2-1=1的字符已经出现过了。
那么根据这个规则,如果出现'b',那么bin的第'b'-'a' = 1位被设为1; 如果出现'f',那么bin的第'f'-'a' = 5位被设为1。
每次遍历到一个字符,便在bin上记录,如果此时有一个已经出现过的字符再次出现,那么由于000100 && 000100 = 1 > 0,即当bin && 1 << dt时,结果大于0.而对于未出现过的字符,由于000100 && 000001 = 0,结果为0.这样就可以区别这个字符是否出现过。
Documentation
¶
There is no documentation for this package.
Source Files
¶
Click to show internal directories.
Click to hide internal directories.