中级农民
- 积分
- 102
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2015-11-19
- 最后登录
- 1970-1-1
|
写个java版本的吧, 楼主上面的例子应该都能过:
- public class FilteredTrie {
- static class TrieNode{
- char ch;
- boolean hasStar= false;
- boolean isEnd= false;
- TrieNode[] children= new TrieNode[26];
- public TrieNode(char ch){
- this.ch= ch;
- }
- @Override
- public String toString(){
- return this.ch+" hasStar:"+ hasStar+ " isEnd:"+ isEnd;
- }
- }
- static class Trie{
- TrieNode root= new TrieNode('*');
- public Trie(String[] words){
- for(String word: words){
- TrieNode node= root;
- for(int i=0; i<word.length(); i++){
- char ch= word.charAt(i);
- if(ch=='*'){
- node.hasStar= true;
- continue;
- }
- if(node.children[ch-'a']==null){
- node.children[ch-'a']= new TrieNode(ch);
- }
- node= node.children[ch-'a'];
- }
- node.isEnd= true;
- }
- }
- public boolean search(String word){
- return search(word, root);
- }
- public boolean search(String word, TrieNode _node){
- if(word.length()==0) return _node.isEnd;
- TrieNode node= _node;
- for(int i=0; i<word.length(); i++){
- char ch= word.charAt(i);
- if(node.hasStar){
- for(int len=0; i+len<=word.length(); i++){
- node.hasStar= false;
- if(search(word.substring(i+len), node)){
- node.hasStar= true;
- return true;
- }
- node.hasStar= true;
- }
- return false;
- }else{
- if(node.children[ch-'a']==null) return false;
- node= node.children[ch-'a'];
- }
- }
- return node.isEnd;
- }
- }
- public static void main(String[] args){
- String[] filters= new String[]{"h*o", "fo*d", "fo*de"};
- Trie trie= new Trie(filters);
- String[] words= new String[]{"food", "hello", "foo", "fod", "foood", "focfd", "fodede"};
- for(String word: words){
- System.out.println(trie.search(word));
- }
- }
- }
复制代码 |
|