单页网站下载/百度推广开户代理
实现Trie(前缀树)
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
哈希集合
class Trie {private Set<String> set;private Set<String> prefixes;public Trie() {set = new HashSet<>();prefixes = new HashSet<>();}public void insert(String word) {set.add(word);for (int i = 0; i < word.length(); i++) prefixes.add(word.substring(0, i + 1));}public boolean search(String word) {return set.contains(word);}public boolean startsWith(String prefix) {return prefixes.contains(prefix);}
}
树形结构
public class Trie {private Trie[] children;private boolean isEnd;public Trie() {children = new Trie[26];isEnd = false;}public void insert(String word) {Trie node = find(word, true);node.isEnd = true;}public boolean search(String word) {Trie node = find(word, false);return node != null && node.isEnd;}public boolean startsWith(String prefix) {return find(prefix, false) != null;}private Trie find(String word, boolean insertMode) {Trie node = this;for (int i = 0; i < word.length(); i++) {int index = word.charAt(i) - 'a';if (node.children[index] == null) {if(insertMode)node.children[index] = new Trie();elsereturn null;}node = node.children[index];}return node;}
}
添加与搜索单词
请你设计一个数据结构,支持 添加新单词 和 查找字符串是否与任何先前添加的字符串匹配 。
实现词典类 WordDictionary :
- WordDictionary() 初始化词典对象
- void addWord(word) 将 word 添加到数据结构中,之后可以对它进行匹配
- bool search(word) 如果数据结构中存在字符串与 word 匹配,则返回 true ;否则,返回 false 。word 中可能包含一些 ‘.’ ,每个 . 都可以表示任何一个字母。
示例:
输入:
[“WordDictionary”,“addWord”,“addWord”,“addWord”,“search”,“search”,“search”,“search”]
[[],[“bad”],[“dad”],[“mad”],[“pad”],[“bad”],[".ad"],[“b…”]]
输出:
[null,null,null,null,false,true,true,true]
解释:
WordDictionary wordDictionary = new WordDictionary();
wordDictionary.addWord(“bad”);
wordDictionary.addWord(“dad”);
wordDictionary.addWord(“mad”);
wordDictionary.search(“pad”); // return False
wordDictionary.search(“bad”); // return True
wordDictionary.search(".ad"); // return True
wordDictionary.search(“b…”); // return True
前缀树存储
class TrieNode {public TrieNode[] children;public boolean isEnd;public TrieNode() {children = new TrieNode[26];isEnd = false;}
}class WordDictionary {private TrieNode root;public WordDictionary() {root = new TrieNode();}public void addWord(String word) {TrieNode node = root;for (int i = 0; i < word.length(); i++) {int index = word.charAt(i) - 'a';if (node.children[index] == null)node.children[index] = new TrieNode();node = node.children[index];}node.isEnd = true;}public boolean search(String word) {return dfs(word, root);}private boolean dfs(String word, TrieNode root) {TrieNode cur = root;char[] array = word.toCharArray();for (int i = 0; i < array.length; i++) {if (array[i] == '.') {for (int j = 0; j < 26; j++) {if (cur.children[j] != null) {if (dfs(word.substring(i + 1), cur.children[j]))return true;}}return false;}if (cur.children[array[i] - 'a'] == null)return false;cur = cur.children[array[i] - 'a'];}return cur.isEnd;}
}
哈希集合存储
class WordDictionary {private Map<Integer, HashSet<String>> map;public WordDictionary() {map = new HashMap<>();}public void addWord(String word) {int len = word.length();HashSet<String> set = map.getOrDefault(len, new HashSet<String>());set.add(word);map.put(len, set);}public boolean search(String word) {int len = word.length();HashSet<String> set = map.getOrDefault(len, new HashSet<String>());if (set.contains(word))return true;for (String s : set) {if (equal(s, word, len))return true;}return false;}private boolean equal(String s, String word, int len) {char[] c1 = s.toCharArray();char[] c2 = word.toCharArray();for (int i = 0; i < len; i++) {if (c1[i] != c2[i] && c2[i] != '.')return false;}return true;}
}
哈希集合数组
按单词长度和首字母分类。
class WordDictionary {private HashSet<String>[][] table;public WordDictionary() {table = new HashSet[500][26];}public void addWord(String word) {int len = word.length();int charIndex = word.charAt(0) - 97;HashSet<String> set = table[len - 1][charIndex];if (set == null) {set = new HashSet<String>();table[len - 1][charIndex] = set;}set.add(word);}public boolean search(String word) {int len = word.length();HashSet<String> set;if ('.' == word.charAt(0)) {HashSet<String>[] setArray = table[len - 1];if (setArray == null || setArray.length == 0)return false;for (int i = 0; i < setArray.length; i++) {set = setArray[i];if (set == null || set.size() == 0)continue;for (String key : set) {if (match(word, key))return true;}}} else {int charIndex = word.charAt(0) - 97;set = table[len - 1][charIndex];if (set == null || set.size() == 0)return false;for (String key: set) {if (match(word, key))return true;}}return false;}private boolean match(String word, String value) {int len = word.length();for (int i = 0; i < len; i++) {if ('.' == word.charAt(i) || word.charAt(i) == value.charAt(i))continue;return false;}return true;}
}
正则表达式
import java.util.regex.*;
class WordDictionary {StringBuilder sb;public WordDictionary() {sb = new StringBuilder();sb.append('#');}public void addWord(String word) {sb.append(word);sb.append('#');}public boolean search(String word) {Pattern p = Pattern.compile('#' + word + '#');Matcher m = p.matcher(sb.toString());return m.find();}
}
数组中两个数的最大异或值
给你一个整数数组 nums ,返回 nums[i] XOR nums[j] 的最大运算结果,其中 0 ≤ i ≤ j < n 。
进阶:你可以在 O(n) 的时间解决这个问题吗?
示例 1:
输入:nums = [3,10,5,25,2,8]
输出:28
解释:最大运算结果是 5 XOR 25 = 28.
示例 2:
输入:nums = [0]
输出:0
示例 3:
输入:nums = [2,4]
输出:6
示例 4:
输入:nums = [8,10,2]
输出:10
示例 5:
输入:nums = [14,70,53,83,49,91,36,80,92,51,66,70]
输出:127
利用前缀树来查找与 当前数字 相异或 值最大的数字
要想找到异或值最大的数字,即尽可能每一位都不相同,且不相同的位数越高越好。
将数字的二进制形式加入前缀树,同时计算该数字在前缀树中所能得到的最大异或值。
class Solution {class TrieNode {TrieNode[] children = new TrieNode[2];}private TrieNode root = new TrieNode();private void initTrie(int[] nums, int top_bit) {for (int num : nums) {TrieNode cur = root;for (int i = top_bit; i >= 0; i--) {int bit = (num >>> i) & 1;TrieNode next = cur.children[bit];if (next == null) {next = new TrieNode();cur.children[bit] = next;}cur = next;}}}public int findMaximumXOR(int[] nums) {int len = nums.length;if (len == 1)return 0;else if (len == 2)return nums[0] ^ nums[1];int maxNum = nums[0];for(int num : nums) maxNum = Math.max(maxNum, num);int top_bit = (Integer.toBinaryString(maxNum)).length();initTrie(nums, top_bit);int maxXor = 0;for (int num : nums) {TrieNode cur = root;int currXor = 0;for (int i = top_bit; i >= 0; i--) {int bit = (num >>> i) & 1, xorBit = bit ^ 1;TrieNode next = cur.children[xorBit];if (next == null) {cur = cur.children[bit];} else {cur = next;currXor |= (1 << i);}}maxXor = Math.max(maxXor, currXor);}return maxXor;}
}
合并建树和查找
class Solution {class TrieNode {TrieNode[] children = new TrieNode[2];}private TrieNode root = new TrieNode();public int findMaximumXOR(int[] nums) {int len = nums.length;if (len == 1)return 0;else if (len == 2)return nums[0] ^ nums[1];int maxNum = nums[0];for(int num : nums) maxNum = Math.max(maxNum, num);int top_bit = (Integer.toBinaryString(maxNum)).length();int maxXor = 0;for (int num : nums) {TrieNode cur = root, xorCur = root;int currXor = 0;for (int i = top_bit; i >= 0; i--) {int bit = (num >>> i) & 1, xorBit = bit ^ 1;TrieNode next = cur.children[bit], xorNext = xorCur.children[xorBit];if (next == null) {next = new TrieNode();cur.children[bit] = next;}cur = next;if (xorNext == null) {xorCur = xorCur.children[bit];} else {xorCur = xorNext;currXor |= (1 << i);}}maxXor = Math.max(maxXor, currXor);}return maxXor;}
}