Add and Search Word - Data structure design
2016-07-10 12:39
393 查看
public class WordDictionary { private class TrieNode { TrieNode[] children = new TrieNode[26]; boolean isExisted; } private TrieNode root; public WordDictionary() { root = new TrieNode(); } // Adds a word into the data structure. public void addWord(String word) { if (word == null || word.length() == 0) { return; } TrieNode node = root; for (int i = 0; i < word.length(); i++) { int c = word.charAt(i) - 'a'; if (node.children[c] == null) { TrieNode child = new TrieNode(); node.children[c] = child; node = child; } else { node = node.children[c]; } } node.isExisted = true; } // Returns if the word is in the data structure. A word could // contain the dot character '.' to represent any one letter. public boolean search(String word) { if (word == null) { return false; } return helper(word, root, 0); } private boolean helper(String word, TrieNode node, int pos) { if (pos == word.length() && node.isExisted) { return true; } if (pos >= word.length()) { return false; } char c = word.charAt(pos); if (c == '.') { for (int i = 0; i < 26; i++) { if (node.children[i] != null) { if (helper(word, node.children[i], pos + 1)) { return true; } } } } else { int idx = c - 'a'; if (node.children[idx] != null) { if (helper(word, node.children[idx], pos + 1)) { return true; } } } return false; } } // Your WordDictionary object will be instantiated and called as such: // WordDictionary wordDictionary = new WordDictionary(); // wordDictionary.addWord("word"); // wordDictionary.search("pattern");
相关文章推荐
- 【HDU】5459 Jesus Is Here(2015ACM/ICPC Shenyang Online)
- VS2010旗舰版无法安装
- Expedia:Subhajit_Mandal Solution
- Space Replacement
- caffe 学习系列 数据层介绍
- 瀑布流UICollectionViewFlowLayout
- shell编程之awk
- 自定义控件(二) 一个圆形钟表
- Linux 查看当前时间
- 利用OS X工具选择合适的无线频段
- 主流开源编解码器Xvid,x264,ffmpeg 性能对比
- java枚举类使用
- partproble在RHEL 6下无法更新分区信息
- java读取本地文件
- (转)Android startActivityForResult(intent, requestCode)的用法
- Code::Blocks代码自动提示设置及常用快捷键
- 完整的社交app源码android+laravel
- 【大型网站技术实践】初级篇:海量图片的分布式存储设计与实现
- 16、getclass兼容方法
- 16.16