huffmanTree之解码

描述:
通常要求根据给定的编码本对密文进行解码。现已给定相应字符的哈夫曼编码,要求根据编码对密文进行解码。
输入:
输入的第一行为出现的字符的个数n,接下来n行为字符及对应字符的哈夫曼编码,相应字符后为冒号和一空格,然后是哈夫曼编码。
然后一个自然数m,表示m行需要进行解码的“0”、“1”符号串。
接下来m行分别为“0”、“1”符号串,即需要解码的串。
输出:
对每一行需要解码的串,进行解码,并输出解码后的结果。
样例输入:
3
a: 00
b: 01
c: 1
2
00000111
0001110001
样例输出:
aabcc

abccab


思路在上几篇的文章中,已经详细解释。在此不再解释。

    文章一:http://blog.csdn.net/zjwsa/article/details/78930331

   文章二:http://blog.csdn.net/zjwsa/article/details/78930200


代码如下:

import java.util.Scanner;

class huffmanTree {
	char ch;
	String p;
}

public class codeHuffmanTree {
	public static int x1, x2;
	public static huffmanTree node[];
	public static int n;

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		n = sc.nextInt();
		/// 构造结点
		node = new huffmanTree[n + 1];
		for (int i = 0; i < n + 1; i++)
			node[i] = new huffmanTree();
		/// 开始输入结点信息
		String code = sc.nextLine();
		for (int i = 1; i <= n; i++) {
			code = sc.nextLine();
			String t[] = code.split(": ");
			node[i].ch = t[0].charAt(0);
			node[i].p = t[1];
		}
		/// 开始读入解码
		int number = sc.nextInt();
		for (int i = 0; i < number; i++) {
			String k = sc.next();
			similation(k);
		}
	}

	private static void similation(String o) {
		String u = "";
		for (int i = 0; i < o.length(); i++) {
			u += o.charAt(i);
			if (i + 1 == o.length()) {
				chase(u, "");
			} else {
				int q = i;
				while (true) {
					x1 = x2 = 0;
					String l = u + o.charAt(i + 1);
					chase(u, l);
					if (x1 != 0 && x2 == 0) {
						System.out.print(node[x1].ch);
						u = "";
						break;
					}
					q++;
					if (q == o.length())
						break;
					u += o.charAt(q);
				}
				i = q;
			}
		}
		System.out.println();
	}

	private static void chase(String u, String string) {
		if (string == "") {
			for (int k = 1; k <= n; k++) {
				if (u.equals(node[k].p)) {
					System.out.print(node[k].ch);
					return;
				}
			}
		} else {
			for (int k = 1; k <= n; k++) {
				if (x1 == 0 && u.equals(node[k].p))
					x1 = k;

				if (x2 == 0 && string.equals(node[k].p))
					x2 = k;
			}
		}
	}
}
posted @ 2017-12-29 13:48  让你一生残梦  阅读(229)  评论(0编辑  收藏  举报