php网站制作,服装品牌网站开发php,高雅大气有寓意的公司取名,怎么在本地安装wordpress题目
请设计实现一棵前缀树Trie#xff0c;它有如下操作。
函数insert#xff0c;在前缀树中添加一个字符串。函数search#xff0c;查找字符串。如果前缀树中包含该字符串#xff0c;则返回true#xff1b;否则返回false。函数startWith#xff0c;查找字符串前缀。如…题目
请设计实现一棵前缀树Trie它有如下操作。
函数insert在前缀树中添加一个字符串。函数search查找字符串。如果前缀树中包含该字符串则返回true否则返回false。函数startWith查找字符串前缀。如果前缀树中包含以该前缀开头的字符串则返回true否则返回false。
例如调用函数insert在前缀树中添加单词goodbye之后输入good调用函数search返回false但输入good调用函数startWith则返回true。再次调用函数insert添加单词good之后此时再输入good调用函数search则返回true。
分析
首先定义前缀树中节点的数据结构。前缀树中的节点对应字符串中的一个字符。如果只考虑英文小写字母那么字符可能是从’a’到’z’的任意一个因此前缀树中的节点可能有26个子节点。可以将26个子节点放到一个数组中数组中的第1个元素是对应字母’a’的子节点第2个元素是对应字母’b’的子节点其余的以此类推。
解
public class Trie {private TrieNode root;public Trie() {root new TrieNode();}class TrieNode {TrieNode children[];boolean isWord;public TrieNode() {children new TrieNode[26];}}public static void main(String[] args) {Trie trie new Trie();trie.insert(apple);System.out.println(trie.search(apple));System.out.println(trie.search(app));System.out.println(trie.startsWith(app));trie.insert(app);System.out.println(trie.search(app));}public void insert(String word) {TrieNode node root;for (char ch : word.toCharArray()) {// 对应的位置存放一个链接相应位置有值则代表有相应的字母if (node.children[ch - a] null) {node.children[ch - a] new TrieNode();}node node.children[ch - a];}node.isWord true;}public boolean search(String word) {TrieNode node root;for (char ch : word.toCharArray()) {if (node.children[ch - a] null) {return false;}node node.children[ch - a];}return node.isWord;}public boolean startsWith(String prefix) {TrieNode node root;for (char ch : prefix.toCharArray()) {if (node.children[ch - a] null) {return false;}node node.children[ch - a];}return true;}
}