数据结构与算法 -- 字符串匹配

1、Trie树

public class TrieTree {
    private TrieNode root = new TrieNode('/');//存储无意义字符
    
    //往Trie树中插入一个字符串
    public void insert(char[] text) {
        TrieNode p = root;
        for(int i=0; i<text.length; i++) {
            int index = text[i] - 'a';
            if(p.children[index] == null) {
                TrieNode newNode = new TrieNode(text[i]);
                p.children[index] = newNode;
            }
            p = p.children[index];
        }
        p.isEndingChar = true;
    }
    
    //在Trie树中查找一个字符串
    public boolean find(char[] pattern) {
        TrieNode p = root;
        for(int i=0; i<pattern.length; i++) {
            int index = pattern[i] - 'a';
            if(p.children[index] == null) {
                return false;//不存在pattern
            }
            p = p.children[index];
        }
        if(p.isEndingChar) {//完全匹配到pattern
            return true;
        }else {//不能完全匹配,只是前缀
            return false;
        }
    }
    public class TrieNode{
        public char data;
        public TrieNode[] children = new TrieNode[26];
        public boolean isEndingChar = false;
        public TrieNode(char data) {
            this.data = data;
        }
    }
    
    public static void main(String[] args) {
        TrieTree trieTree = new TrieTree();
        trieTree.insert("hello".toCharArray());
        trieTree.insert("world".toCharArray());
        trieTree.insert("word".toCharArray());
        trieTree.insert("teacher".toCharArray());
        trieTree.insert("wild".toCharArray());
        String pattern = "word";
        System.out.println(trieTree.find(pattern.toCharArray()) ? "找到了 " + pattern : "没有完全匹配的字符串 " + pattern);
        pattern = "wor";
        System.out.println(trieTree.find(pattern.toCharArray()) ? "找到了 " + pattern : "没有完全匹配的字符串 " + pattern);
    }
}

猜你喜欢

转载自www.cnblogs.com/jiangwangxiang/p/11106262.html