4.字典树练习题

字典树模板

class Trie {
    class TrieNode{//字典树的结点数据结构
		boolean end;//是否是单词末尾的标识
		TrieNode[] child; //26个小写字母的拖尾
		public TrieNode(){
			end = false;
			child = new TrieNode[26];
		}
	}

	TrieNode root;//字典树的根节点。
	
    public Trie() {
        root = new TrieNode();
    }

    public void insert(String s) {
        TrieNode p = root;
        for(int i = 0; i < s.length(); i++) {
            int u = s.charAt(i) - 'a';
			//若当前结点下没有找到要的字母,则新开结点继续插入
            if (p.child[u] == null) p.child[u] = new TrieNode();
            p = p.child[u]; 
        }
        p.end = true;
    }

    public boolean search(String s) {
        TrieNode p = root;
        for(int i = 0; i < s.length(); i++) {
            int u = s.charAt(i) - 'a';
            if (p.child[u] == null) return false;//变化点(根据题意)
            p = p.child[u]; 
        }
        return p.end;
    }

    public boolean startsWith(String s) {
        TrieNode p = root;
        for(int i = 0; i < s.length(); i++) {
            int u = s.charAt(i) - 'a';
            if (p.child[u] == null) return false;
            p = p.child[u]; 
        }
        return true;
    }
}

字典树练习题

208. 实现 Trie (前缀树)

难度中等1418

Trie(发音类似 “try”)或者说 前缀树 是一种树形数据结构,用于高效地存储和检索字符串数据集中的键。这一数据结构有相当多的应用情景,例如自动补完和拼写检查。

请你实现 Trie 类:

  • Trie() 初始化前缀树对象。
  • void insert(String word) 向前缀树中插入字符串 word
  • boolean search(String word) 如果字符串 word 在前缀树中,返回 true(即,在检索之前已经插入);否则,返回 false
  • boolean startsWith(String prefix) 如果之前已经插入的字符串 word 的前缀之一为 prefix ,返回 true ;否则,返回 false

示例:

输入
["Trie", "insert", "search", "search", "startsWith", "insert", "search"]
[[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]]
输出
[null, null, true, false, true, null, true]

解释
Trie trie = new Trie();
trie.insert("apple");
trie.search("apple");   // 返回 True
trie.search("app");     // 返回 False
trie.startsWith("app"); // 返回 True
trie.insert("app");
trie.search("app");     // 返回 True

提示:

  • 1 <= word.length, prefix.length <= 2000
  • wordprefix 仅由小写英文字母组成
  • insertsearchstartsWith 调用次数 总计 不超过 3 * 104
class Trie {
    class TrieNode {
        boolean end;
        TrieNode[] child;
        public TrieNode(){
            end = false;
            child = new TrieNode[26];
        }
    }

    TrieNode root;

    public Trie() {
        root = new TrieNode();
    }
    
    public void insert(String s) {
        TrieNode p = root;
        for(int i = 0; i < s.length(); i++){
            int u = s.charAt(i) - 'a';
            if(p.child[u] == null) p.child[u] = new TrieNode();
            p = p.child[u];
        }
        p.end = true;
    }
    
    public boolean search(String s) {
        TrieNode p = root;
        for(int i = 0; i < s.length(); i++){
            int u = s.charAt(i) - 'a';
            if(p.child[u] == null) return false;
            p = p.child[u];
        }
        return p.end;
    }
    
    public boolean startsWith(String s) {
        TrieNode p = root;
        for(int i = 0; i < s.length(); i++){
            int u = s.charAt(i) - 'a';
            if(p.child[u] == null) return false;
            p = p.child[u];
        }
        return true;
    }
}

1032. 字符流

难度困难160

设计一个算法:接收一个字符流,并检查这些字符的后缀是否是字符串数组 words 中的一个字符串。

例如,words = ["abc", "xyz"] 且字符流中逐个依次加入 4 个字符 'a''x''y''z' ,你所设计的算法应当可以检测到 "axyz" 的后缀 "xyz"words 中的字符串 "xyz" 匹配。

按下述要求实现 StreamChecker 类:

  • StreamChecker(String[] words) :构造函数,用字符串数组 words 初始化数据结构。
  • boolean query(char letter):从字符流中接收一个新字符,如果字符流中的任一非空后缀能匹配 words 中的某一字符串,返回 true ;否则,返回 false

示例:

输入:
["StreamChecker", "query", "query", "query", "query", "query", "query", "query", "query", "query", "query", "query", "query"]
[[["cd", "f", "kl"]], ["a"], ["b"], ["c"], ["d"], ["e"], ["f"], ["g"], ["h"], ["i"], ["j"], ["k"], ["l"]]
输出:
[null, false, false, false, true, false, true, false, false, false, false, false, true]

解释:
StreamChecker streamChecker = new StreamChecker(["cd", "f", "kl"]);
streamChecker.query("a"); // 返回 False
streamChecker.query("b"); // 返回 False
streamChecker.query("c"); // 返回n False
streamChecker.query("d"); // 返回 True ,因为 'cd' 在 words 中
streamChecker.query("e"); // 返回 False
streamChecker.query("f"); // 返回 True ,因为 'f' 在 words 中
streamChecker.query("g"); // 返回 False
streamChecker.query("h"); // 返回 False
streamChecker.query("i"); // 返回 False
streamChecker.query("j"); // 返回 False
streamChecker.query("k"); // 返回 False
streamChecker.query("l"); // 返回 True ,因为 'kl' 在 words 中

提示:

  • 1 <= words.length <= 2000
  • 1 <= words[i].length <= 200
  • words[i] 由小写英文字母组成
  • letter 是一个小写英文字母
  • 最多调用查询 4 * 104

题解:反向建字典树,反向查询字符流

class StreamChecker {

    Trie trie;
    List<Character> list;

    public StreamChecker(String[] words) {
        trie = new Trie();
        list = new ArrayList<>();
        for(String w : words){
            trie.insert(new StringBuilder(w).reverse().toString());
        }
    }
    
    public boolean query(char letter) {
        list.add(letter);
        return trie.search(list);
    }
}


class Trie {
    class TrieNode{//字典树的结点数据结构
		boolean end;//是否是单词末尾的标识
		TrieNode[] child; //26个小写字母的拖尾
		public TrieNode(){
			end = false;
			child = new TrieNode[26];
		}
	}

	TrieNode root;//字典树的根节点。
	
    public Trie() {
        root = new TrieNode();
    }

    public void insert(String s) {
        TrieNode p = root;
        for(int i = 0; i < s.length(); i++) {
            int u = s.charAt(i) - 'a';
			//若当前结点下没有找到要的字母,则新开结点继续插入
            if (p.child[u] == null) p.child[u] = new TrieNode();
            p = p.child[u]; 
        }
        p.end = true;
    }

    public boolean search(List<Character> list) {
        TrieNode p = root;
        for(int i = list.size() - 1; i >= 0; i--) {
            int u = list.get(i) - 'a';
            if(p.end == true) return true;
            if (p.child[u] == null) return false;
            p = p.child[u]; 
        }
        return p.end;
    }

}

648. 单词替换

难度中等272

在英语中,我们有一个叫做 词根(root) 的概念,可以词根后面添加其他一些词组成另一个较长的单词——我们称这个词为 继承词(successor)。例如,词根an,跟随着单词 other(其他),可以形成新的单词 another(另一个)。

现在,给定一个由许多词根组成的词典 dictionary 和一个用空格分隔单词形成的句子 sentence。你需要将句子中的所有继承词词根替换掉。如果继承词有许多可以形成它的词根,则用最短的词根替换它。

你需要输出替换之后的句子。

示例 1:

输入:dictionary = ["cat","bat","rat"], sentence = "the cattle was rattled by the battery"
输出:"the cat was rat by the bat"

示例 2:

输入:dictionary = ["a","b","c"], sentence = "aadsfasf absbs bbab cadsfafs"
输出:"a a b c"

提示:

  • 1 <= dictionary.length <= 1000
  • 1 <= dictionary[i].length <= 100
  • dictionary[i] 仅由小写字母组成。
  • 1 <= sentence.length <= 10^6
  • sentence 仅由小写字母和空格组成。
  • sentence 中单词的总量在范围 [1, 1000] 内。
  • sentence 中每个单词的长度在范围 [1, 1000] 内。
  • sentence 中单词之间由一个空格隔开。
  • sentence 没有前导或尾随空格。

题解:search时查看有没有到end

class Solution {
    public String replaceWords(List<String> dictionary, String sentence) {
        Trie trie = new Trie(dictionary);
        String[] strs = sentence.split(" ");
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < strs.length; i++){
            sb.append(trie.search(strs[i]));
            if(i != strs.length-1) sb.append(" ");
        } 
        return sb.toString();
    }
}
class Trie {
    class trieNode {
        boolean end;
        trieNode[] child;
        public trieNode() {
            end = false;
            child = new trieNode[26];
        }
    }

    trieNode root;

    public Trie(List<String> dictionary){
        root = new trieNode();
        for(int i = 0; i < dictionary.size(); i++){
            this.insert(dictionary.get(i));
        }
    }

    public void insert(String s){
        trieNode p = root;
        for(int i = 0; i < s.length(); i++){
            int u = s.charAt(i) - 'a';
            if(p.child[u] == null) p.child[u] = new trieNode();
            p = p.child[u];
        }
        p.end = true;
    }

    public String search(String s){
        trieNode p = root;
        for(int i = 0; i < s.length(); i++){
            int u = s.charAt(i) - 'a';
            if(p.end == true) return s.substring(0,i);
            if(p.child[u] == null) return s;
            p = p.child[u];
        }
        return s;
    }

}

720. 词典中最长的单词

难度中等330

给出一个字符串数组 words 组成的一本英语词典。返回 words 中最长的一个单词,该单词是由 words 词典中其他单词逐步添加一个字母组成。

若其中有多个可行的答案,则返回答案中字典序最小的单词。若无答案,则返回空字符串。

示例 1:

输入:words = ["w","wo","wor","worl", "world"]
输出:"world"
解释: 单词"world"可由"w", "wo", "wor", 和 "worl"逐步添加一个字母组成。

示例 2:

输入:words = ["a", "banana", "app", "appl", "ap", "apply", "apple"]
输出:"apple"
解释:"apply" 和 "apple" 都能由词典中的单词组成。但是 "apple" 的字典序小于 "apply" 

提示:

  • 1 <= words.length <= 1000
  • 1 <= words[i].length <= 30
  • 所有输入的字符串 words[i] 都只包含小写字母。
class Solution {
    public String longestWord(String[] words) {
        Arrays.sort(words);
        Trie trie = new Trie();
        for(String s : words){
            trie.insert(s);
        }
        String res = "";
        for(int i = 0; i < words.length; i++){
            if(trie.search(words[i]) && words[i].length() > res.length()){
                res = words[i];
            }
        }
        return res;
    }
}

class Trie {
    class TrieNode{//字典树的结点数据结构
		boolean end;//是否是单词末尾的标识
		TrieNode[] child; //26个小写字母的拖尾
		public TrieNode(){
			end = false;
			child = new TrieNode[26];
		}
	}

	TrieNode root;//字典树的根节点。
	
    public Trie() {
        root = new TrieNode();
        root.end = true;
    }

    public void insert(String s) {
        TrieNode p = root;
        for(int i = 0; i < s.length(); i++) {
            int u = s.charAt(i) - 'a';
			//若当前结点下没有找到要的字母,则新开结点继续插入
            if (p.child[u] == null) p.child[u] = new TrieNode();
            p = p.child[u]; 
        }
        p.end = true;
    }

    public boolean search(String s) {
        TrieNode p = root;
        for(int i = 0; i < s.length(); i++) {
            int u = s.charAt(i) - 'a';
            if (p.child[u] == null || p.end == false) return false;
            p = p.child[u]; 
        }
        return p.end;
    }

}

676. 实现一个魔法字典

难度中等214

设计一个使用单词列表进行初始化的数据结构,单词列表中的单词 互不相同 。 如果给出一个单词,请判定能否只将这个单词中一个字母换成另一个字母,使得所形成的新单词存在于你构建的字典中。

实现 MagicDictionary 类:

  • MagicDictionary() 初始化对象
  • void buildDict(String[] dictionary) 使用字符串数组 dictionary 设定该数据结构,dictionary 中的字符串互不相同
  • bool search(String searchWord) 给定一个字符串 searchWord ,判定能否只将字符串中 一个 字母换成另一个字母,使得所形成的新字符串能够与字典中的任一字符串匹配。如果可以,返回 true ;否则,返回 false

示例:

输入
["MagicDictionary", "buildDict", "search", "search", "search", "search"]
[[], [["hello", "leetcode"]], ["hello"], ["hhllo"], ["hell"], ["leetcoded"]]
输出
[null, null, false, true, false, false]

解释
MagicDictionary magicDictionary = new MagicDictionary();
magicDictionary.buildDict(["hello", "leetcode"]);
magicDictionary.search("hello"); // 返回 False
magicDictionary.search("hhllo"); // 将第二个 'h' 替换为 'e' 可以匹配 "hello" ,所以返回 True
magicDictionary.search("hell"); // 返回 False
magicDictionary.search("leetcoded"); // 返回 False

提示:

  • 1 <= dictionary.length <= 100
  • 1 <= dictionary[i].length <= 100
  • dictionary[i] 仅由小写英文字母组成
  • dictionary 中的所有字符串 互不相同
  • 1 <= searchWord.length <= 100
  • searchWord 仅由小写英文字母组成
  • buildDict 仅在 search 之前调用一次
  • 最多调用 100search

方法一:字典树 + DFS回溯

class MagicDictionary {

    Trie trie;

    public MagicDictionary() {
        trie = new Trie();
    }
    
    public void buildDict(String[] dictionary) {
        for(String d : dictionary)
            trie.insert(d);
    }
    
    public boolean search(String searchWord) {
        TrieNode cur = trie.root;
        return trie.dfs(cur, searchWord, 0, 0);
    }
}

class TrieNode{//字典树的结点数据结构
    boolean end;//是否是单词末尾的标识
    TrieNode[] child; //26个小写字母的拖尾
    public TrieNode(){
        end = false;
        child = new TrieNode[26];
    }
}

class Trie {

	TrieNode root;//字典树的根节点。
	
    public Trie() {
        root = new TrieNode();
    }

    public void insert(String s) {
        TrieNode p = root;
        for(int i = 0; i < s.length(); i++) {
            int u = s.charAt(i) - 'a';
			//若当前结点下没有找到要的字母,则新开结点继续插入
            if (p.child[u] == null) p.child[u] = new TrieNode();
            p = p.child[u]; 
        }
        p.end = true;
    }

    public boolean dfs(TrieNode cur, String word, int idx, int cnt) {
        if(idx == word.length()){
            if(cnt == 1 && cur.end) return true;
            else return false;
        }
        // 遍历cur节点的所有子树
        for(int i = 0; i < 26; i++){
            if(cur.child[i] == null) continue;
            if(word.charAt(idx)-'a' == i){ // 与word[idx]字母相同,不用替换
                if(dfs(cur.child[i], word, idx+1, cnt)) 
                return true;
            }else if(cnt == 0 && (word.charAt(idx)-'a' != i)){
                if(dfs(cur.child[i], word, idx+1, cnt+1))
                    return true;
            }
        }
        return false;
    }
}

另一种写法:

class MagicDictionary {

    Trie trie;

    public MagicDictionary() {
        trie = new Trie();
    }
    
    public void buildDict(String[] dictionary) {
        for(String a : dictionary){
            trie.insert(a);
        }
    }
    
    public boolean search(String searchWord) {
        return trie.search(searchWord);
    }
}

class Trie {

    class TrieNode{
        boolean end;
        TrieNode[] child;
        public TrieNode(){
            end = false;
            child = new TrieNode[26];
        };
    }

    TrieNode root;

    public Trie() { 
        root = new TrieNode();
    }
    
    public void insert(String word) {
        TrieNode p = root;
        for(int i = 0; i < word.length(); i++){
            int u = word.charAt(i)-'a';
            if(p.child[u] == null) p.child[u] = new TrieNode();
            p = p.child[u];
        }
        p.end = true;
    }
    
    public boolean search(String word) {
        TrieNode p = root;
        return searchReplace(word,0,p,1);
    }

    public boolean searchReplace(String word, int i, TrieNode p,int chance){
        if(i == word.length()){
            return p.end && chance == 0;
        }
        int c = word.charAt(i) - 'a';
        if(p.child[c] == null){
            if(chance == 0){
                return false;
            }
        }

        if(p.child[c] != null){
            boolean res = searchReplace(word,i+1, p.child[c], chance);
            if(res){
                return true;
            }
        }
        for(int j = 0; j < 26; j++){
            if(p.child[j] != null && c != j){
                boolean res = searchReplace(word,i+1, p.child[j], chance-1);
                if(res) return true;
            }
        }
        return false;
        
    }

}

820. 单词的压缩编码

难度中等311

单词数组 words有效编码 由任意助记字符串 s 和下标数组 indices 组成,且满足:

  • words.length == indices.length
  • 助记字符串 s'#' 字符结尾
  • 对于每个下标 indices[i]s 的一个从 indices[i] 开始、到下一个 '#' 字符结束(但不包括 '#')的 子字符串 恰好与 words[i] 相等

给你一个单词数组 words ,返回成功对 words 进行编码的最小助记字符串 s 的长度 。

示例 1:

输入:words = ["time", "me", "bell"]
输出:10
解释:一组有效编码为 s = "time#bell#" 和 indices = [0, 2, 5] 。
words[0] = "time" ,s 开始于 indices[0] = 0 到下一个 '#' 结束的子字符串,如加粗部分所示 "time#bell#"
words[1] = "me" ,s 开始于 indices[1] = 2 到下一个 '#' 结束的子字符串,如加粗部分所示 "time#bell#"
words[2] = "bell" ,s 开始于 indices[2] = 5 到下一个 '#' 结束的子字符串,如加粗部分所示 "time#bell#"

示例 2:

输入:words = ["t"]
输出:2
解释:一组有效编码为 s = "t#" 和 indices = [0] 。

提示:

  • 1 <= words.length <= 2000
  • 1 <= words[i].length <= 7
  • words[i] 仅由小写字母组成
class Solution {
    // 将words中的字符串都逆序,然后按字典序从大到小排序
    // 遍历words数组,判断是否存在以words[i]为前缀的字符串,存在则跳过,不存在则插入字典树并计算答案
    public int minimumLengthEncoding(String[] words) {
        Trie trie = new Trie();
        for(int i = 0; i < words.length; i++){
            words[i] = new StringBuilder(words[i]).reverse().toString();
        }
        Arrays.sort(words, (a, b) -> b.compareTo(a)); // 按照字典序从大到小排序
        int ans = 0;
        for(String word : words){
            if(trie.startsWith(word)) continue;
            trie.insert(word);
            ans += word.length() + 1;
        }
        return ans;
    }
}

class Trie {
    class TrieNode{//字典树的结点数据结构
		boolean end;//是否是单词末尾的标识
		int pass; // 经过这个结点的次数(根据需要设置这个变量)
		TrieNode[] child; //26个小写字母的拖尾
		public TrieNode(){
			end = false;
			pass = 0;
			child = new TrieNode[26];
		}
	}

	TrieNode root;//字典树的根节点。
	
    public Trie() {
        root = new TrieNode();
    }

    public void insert(String s) {
        TrieNode p = root;
        for(int i = 0; i < s.length(); i++) {
            int u = s.charAt(i) - 'a';
			//若当前结点下没有找到要的字母,则新开结点继续插入
            if (p.child[u] == null) p.child[u] = new TrieNode();
            p = p.child[u]; 
            p.pass++;
        }
        p.end = true;
    }

    public boolean search(String s) {
        TrieNode p = root;
        for(int i = 0; i < s.length(); i++) {
            int u = s.charAt(i) - 'a';
            if (p.child[u] == null) return false;//变化点(根据题意)
            p = p.child[u]; 
        }
        return p.end;
    }

    public boolean startsWith(String s) {
        TrieNode p = root;
        for(int i = 0; i < s.length(); i++) {
            int u = s.charAt(i) - 'a';
            if (p.child[u] == null) return false;
            p = p.child[u]; 
        }
        return true;
    }
}

677. 键值映射

难度中等235

设计一个 map ,满足以下几点:

  • 字符串表示键,整数表示值
  • 返回具有前缀等于给定字符串的键的值的总和

实现一个 MapSum 类:

  • MapSum() 初始化 MapSum 对象
  • void insert(String key, int val) 插入 key-val 键值对,字符串表示键 key ,整数表示值 val 。如果键 key 已经存在,那么原来的键值对 key-value 将被替代成新的键值对。
  • int sum(string prefix) 返回所有以该前缀 prefix 开头的键 key 的值的总和。

示例 1:

输入:
["MapSum", "insert", "sum", "insert", "sum"]
[[], ["apple", 3], ["ap"], ["app", 2], ["ap"]]
输出:
[null, null, 3, null, 5]

解释:
MapSum mapSum = new MapSum();
mapSum.insert("apple", 3);  
mapSum.sum("ap");           // 返回 3 (apple = 3)
mapSum.insert("app", 2);    
mapSum.sum("ap");           // 返回 5 (apple + app = 3 + 2 = 5)

提示:

  • 1 <= key.length, prefix.length <= 50
  • keyprefix 仅由小写英文字母组成
  • 1 <= val <= 1000
  • 最多调用 50insertsum
class MapSum {
    // 用一个map保存已经插入的键值对,使用字典树保存插入的字符串,插入字符串时,更新路径和
    // 插入字符串时先进行判断,如果当前key已经插入过了,再次插入时值需要更新为对应的变化量 v2-v1
    // 求以prefix为前缀的路径和时直接返回p.pass

    Trie trie;
    Map<String, Integer> map = new HashMap<>();

    /** Initialize your data structure here. */
    public MapSum() {
        trie = new Trie();
    }
    
    public void insert(String key, int val) {
        if(map.containsKey(key)){
            // 如果键key已经存在,那么再次插入时插入对应的变化量 v2 - v1
            trie.insert(key, val - map.get(key));
        }else{
            trie.insert(key, val);
        }
        map.put(key, val);
    }
    
    public int sum(String prefix) {
        return trie.startsWith(prefix);
    }
}

class Trie {
    class TrieNode{//字典树的结点数据结构
		boolean end;//是否是单词末尾的标识
		int pass; // 经过这个节点的值的和
		TrieNode[] child; //26个小写字母的拖尾
		public TrieNode(){
			end = false;
			pass = 0;
			child = new TrieNode[26];
		}
	}

	TrieNode root;//字典树的根节点。
	
    public Trie() {
        root = new TrieNode();
    }

    public void insert(String s, int val) {
        TrieNode p = root;
        for(int i = 0; i < s.length(); i++) {
            int u = s.charAt(i) - 'a';
			//若当前结点下没有找到要的字母,则新开结点继续插入
            if (p.child[u] == null) p.child[u] = new TrieNode();
            p = p.child[u]; 
            p.pass += val;
        }
        p.end = true;
    }

    public boolean search(String s) {
        TrieNode p = root;
        for(int i = 0; i < s.length(); i++) {
            int u = s.charAt(i) - 'a';
            if (p.child[u] == null) return false;//变化点(根据题意)
            p = p.child[u]; 
        }
        return p.end;
    }

    public int startsWith(String s) {
        TrieNode p = root;
        int sum = 0;
        for(int i = 0; i < s.length(); i++) {
            int u = s.charAt(i) - 'a';
            // 不存在以 s 为前缀的字符串
            if (p.child[u] == null) return 0;
            p = p.child[u]; 
        }
        return p.pass;
    }
}

421. 数组中两个数的最大异或值

难度中等539

给你一个整数数组 nums ,返回 nums[i] XOR nums[j] 的最大运算结果,其中 0 ≤ i ≤ j < n

示例 1:

输入:nums = [3,10,5,25,2,8]
输出:28
解释:最大运算结果是 5 XOR 25 = 28.

示例 2:

输入:nums = [14,70,53,83,49,91,36,80,92,51,66,70]
输出:127

提示:

  • 1 <= nums.length <= 2 * 105
  • 0 <= nums[i] <= 231 - 1

题解:yukiyama

【前缀树+贪心思想,102ms,击败76%】

非常好的一道前缀树非典型应用题。顺便也利用这题复习一下位运算。另外针对官方题解的前缀树代码,我提一点建议,即让search方法(官解中的check方法)返回匹配num的具有最多相反位的数,而不是它们异或的结果。毕竟还是要松耦合,让代码看起来更合理流畅。

【讲解】

将num转换为二进制数来思考,要求num1 ^ num2尽量大,即希望num1和num2相反的对应位尽可能多。遍历nums,对当前num寻找与他对应相反位最多的数字求异或。因为是沿着位搜索,这引导我们采用前缀树处理。在本问题中前缀树为二叉树,每个结点具有两个儿子结点,分别表示0和1。遍历nums,将对每一个num执行前缀树的insert操作,完成前缀树的构建。然后再遍历一次nums,对每一个num,查找「与num对应相反位」最多的前缀。与常规前缀树search方法不同的是,本题中要沿着0-1相反的路径搜索。没有相反结点时才沿着唯一结点前进。每次search完更新最大值max。

实际上我们可以一边insert一遍search来完成max的更新,当insert结束时即完成求解。这实际上是贪心思想的体现,此题「贪心」的正确性可以这么理解:假设x ^ y为答案,且x在数组中的位置位于y之前,由于我们一边把数字存入前缀树中,一边更新最大值max,那么在将y存入字典树时,必然会找到x(x必然已在树中)来更新当前的max,此时就会取得max。

  • 时间复杂度:O(31*n),insert和search一个数需要的步数都是固定的31步(for中的30到0),因此插入n个数时间复杂度为 O(31 * n),搜索一个数的时间复杂度为O(31)。
  • 空间复杂度:O(31 * 2 * n),n个数,每个数在前缀树上至多需要31*2来表示。说「至多」是因为,若两个数字的二进制表示的有相同前缀,则前缀部分是「复用」的。
class Solution {
    public int findMaximumXOR(int[] nums) {
        Trie trie = new Trie();
        int ans = 0; // 两个非负数的异或必为非负数
        for(int num : nums){
            trie.insert(num);
            ans = Math.max(ans, trie.search(num) ^ num);
        }
        return ans;
    }
}

class Trie {
    class TrieNode{//字典树的结点数据结构
		TrieNode[] child; // 二进制表示拖尾,只有 0 和 1 
		public TrieNode(){
			child = new TrieNode[2];
		}
	}

	TrieNode root;//字典树的根节点
	
    public Trie() {
        root = new TrieNode();
    }

    public void insert(int num) {
        TrieNode p = root;
        for(int i = 30; i >= 0; i--){ // 题目范围为非负数,高31位移动到低1位只要右移30位
            int bit = (num >> i) & 1;
            if(p.child[bit] == null){
                p.child[bit] = new TrieNode();
            }
            p = p.child[bit];
        }
    }

    // 返回当前前缀树中与num做异或能够取得最大值的数字。取出后再在外部做异或运算。
    public int search(int num) {
        TrieNode p = root;
        int ans = 0;
        for(int i = 30; i >= 0; i--){
            int bit = (num >> i) & 1; // 取得第 i 位 (0或1)
            // 与bit相反(指0-1相反)的节点若不存在,bit不变,若存在,取相反
            bit = p.child[bit ^ 1] == null ? bit : bit ^ 1; 
            ans += bit << i; // 累计ans
            p = p.child[bit];
        }
        return ans;
    }
}

/*
    本题中心思想:要找出异或最大的数,就要找出,从最高位开始尽量和x二进位相反的节点
    举例介绍:  解释int getVal(int x)方法
    在x=5之前的数为(1,3,5)
    建立了一个这样的树
        0              1
     0     1         0 
       1     1         1
    当x=5(即101)时
    1. 第一层选择0(与x的第一位不同)             对应代码if(p.ns[b] != null)
    2. 第二层选择1(与x的第二位不同),指向右子树  对应代码if(p.ns[b] != null)
    3. 第三层只能选择1(因为只有1),指向右子树    对应代码else
    最后选择的时011(即3),此时最大值3^5=6
*/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值