剑指 Offer II 062. 实现前缀树 - 力扣(LeetCode) (leetcode-cn.com)
class Trie {
private Trie[] child;
private boolean isend;
/** Initialize your data structure here. */
public Trie() {
child = new Trie[26];
isend = false;
}
/*
插入字符串的过程为
*/
/** Inserts a word into the trie. */
public void insert(String word) {
Trie node = this;
int length = word.length();
char[] chars = word.toCharArray();
for(int i = 0;i<length;i++){
int index = chars[i]-'a';
if(node.child[index] == null){
node.child[index] = new Trie();
}
node = node.child[index];
}
node.isend = true;
}
/** Returns if the word is in the trie. */
public boolean search(String word) {
Trie ret = searchfix(word);
return ret!=null && ret.isend;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
Trie ret = searchfix(prefix);
return ret!=null;
}
public Trie searchfix(String pix){
Trie node = this;
for(int i = 0;i<pix.length();i++){
int index = pix.charAt(i)-'a';
if(node.child[index]==null){
return null;
}else{
node = node.child[index];
}
}
return node;
}
}
前缀树示例
数据结构
前缀树也称为字典树
节点有一个指向26大小的Trie类型数组存储下一位字符,isEnd字段标识是否结尾
插入过程
从字典树的根开始插入字符串,对于当前字符对应的子节点,有两种情况:
- 子节点存在,沿着字符对应子节点移动到子节点,处理下一个字符
- 子节点不存在node.child[index] == null ,创建一个子节点,放在在数组的对应位置上,然后移动到子节点继续搜索
直到处理完最后一个字符,然后当前节点标记为字符串结尾isEnd = true
查找过程
查找前缀和查找整个的区别为结尾isEnd的值
所以分为了两个方法
- search
- 判断结果为查找到前缀且为字符串结尾isEnd为true
- searchswoth
- 判断结果为查找到前缀
searchfix方法
为查找前缀的过程
当从根开始查找前缀,遍历带查找字符串
- 当前字符的子节点如果为null 表示不存在这个字符串直接返回null
- 当前字符的子节点存在就移动到子节点,继续搜索下一个字符
当循环结束就返回当前指针值为字符串最后一个字符代表的Trie的引用地址,
剑指 Offer 15. 二进制中1的个数 - 力扣(LeetCode) (leetcode-cn.com)
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int total = 0;
while(n!=0){
if((n&1)==1){
total++;
}
n = n>>>1;
}
return total;
}
}
结束条件
以0位结束条件
过程
- 将n与1进行按位与则为
00000000000000000000000000001011
00000000000000000000000000000001
-----------------------------------
00000000000000000000000000000001
最后一位如果为1则值为1,为0则为0
- 一次循环之后将n进行>>>(无符号右移 : 右移后左侧补0)操作
1957. 删除字符使字符串变好 - 力扣(LeetCode) (leetcode-cn.com)
class Solution {
public String makeFancyString(String s) {
int j = 0;
char[] chars = s.toCharArray();
char a = chars[0];
StringBuilder ret = new StringBuilder();
for(int i =0;i<s.length();i++){
if(chars[i] == a){
j++;
if(j>=3){
continue;
}
}else{
a = chars[i];
j=1;
}
ret.append(chars[i]);
}
return ret.toString();
}
}
class Solution {
public String makeFancyString(String s) {
if(s.length()<=2){
return s;
}
StringBuilder sb = new StringBuilder();
char[] chars = s.toCharArray();
int i = 0;
for(;i+2 < s.length(); i++){
if(chars[i]== chars[i+1]&& chars[i] == chars[i+2]){
continue;
}else{
sb.append(chars[i]);
}
}
for(;i<s.length();i++){
sb.append(chars[i]);
}
return sb.toString();
}
}