數據結構與算法(JAVA版)5_2:前綴樹Part2:可插入並檢索任意字符

package com.inspire.chapter5;

import java.util.HashMap;

public class TrieTree2 {

	public static class Node1 {
		public int pass;
		public int end;
		public HashMap<Integer, Node1> nexts;

		public Node1() {
			pass = 0;
			end = 0;
			nexts = new HashMap<>();
		}
	}

	public static class Trie1 {
		private Node1 root;

		public Trie1() {
			root = new Node1();
		}

		// 插入字符串
		public void insert(String word) {
			if (word == null) {
				return;
			}
			char[] str = word.toCharArray();
			Node1 node = root;
			node.pass++;
			int path = 0;
			for (int i = 0; i < str.length; i++) {// 從左往右遍歷字符
				path = (int) str[i];// 由字符對應成走那條路
				if (!node.nexts.containsKey(path)) {
					node.nexts.put(path, new Node1());
				}
				node = node.nexts.get(path);
				node.pass++;
			}
			node.end++;
		}

		// 查詢指定字符串出現的次數
		public int search(String word) {
			if (word == null) {
				return 0;
			}
			char[] str = word.toCharArray();
			Node1 node = root;
			int index = 0;
			for (int i = 0; i < str.length; i++) {
				index = (int) str[i];
				if (!node.nexts.containsKey(index)) {
					return 0;
				}
				node = node.nexts.get(index);
			}
			return node.end;
		}

		// 所有加入的字符串中,有幾個是以pre這個字符串作爲前綴的
		public int prefixNumber(String pre) {
			if (pre == null) {
				return 0;
			}
			char[] str = pre.toCharArray();
			Node1 node = root;
			int index = 0;
			for (int i = 0; i < str.length; i++) {
				index = (int) str[i];
				if (!node.nexts.containsKey(index)) {
					return 0;
				}
				node = node.nexts.get(index);
			}
			return node.pass;
		}

		// 刪除指定字符串
		public void delete(String word) {
			if (search(word) != 0) {
				char[] str = word.toCharArray();
				Node1 node = root;
				node.pass--;
				int path = 0;
				for (int i = 0; i < str.length; i++) {
					path = (int) str[i];
					if (--node.nexts.get(path).pass == 0) {
						node.nexts.remove(path);
						return;
					}
					node = node.nexts.get(path);
				}
				node.end--;
			}
		}

	}

	public static void main(String[] args) {
		Trie1 trie1 = new Trie1();
		String[] str = { "#bC", "abcd", "dfg", "ddd", "#bC" };
		for (int i = 0; i < str.length; i++) {
			trie1.insert(str[i]);
		}

		trie1.delete("#bC");
		int n = trie1.search("#bC");
		System.out.println(n);
	}

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章