ACM HDOJ 1251 (统计难题 )

12 篇文章 0 订阅
5 篇文章 0 订阅

题目链接 http://acm.hdu.edu.cn/showproblem.php?pid=1251

程序一 字典树

import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		Scanner scn = new Scanner(System.in);
		Trie trie = new Trie();
		while (scn.hasNext()) {
			String word = scn.nextLine();
			if (0 == word.length()) {
				break;
			}
			trie.insert(word);
		}
		while (scn.hasNext()) {
			String word = scn.nextLine();
			System.out.println(trie.search(word));
		}
		scn.close();
	}

}

class Trie {

	private Node root;

	public Trie() {
		root = new Node(new Node[26], 0);
	}

	public void insert(String word) {
		Node current = root;
		for (int i = 0; i < word.length(); ++i) {
			if (null != current.getChildrenItem(word.charAt(i) - 'a')) {
				current = current.getChildrenItem(word.charAt(i) - 'a');
				current.setCount(current.getCount() + 1);
			} else {
				Node newNode = new Node(new Node[26], 1);
				current.setChildrenItem(word.charAt(i) - 'a', newNode);
				current = newNode;
			}
		}
	}

	public int search(String word) {
		Node current = root;
		for (int i = 0; i < word.length(); ++i) {
			if (null != current.getChildrenItem(word.charAt(i) - 'a')) {
				current = current.getChildrenItem(word.charAt(i) - 'a');
			} else {
				return 0;
			}
		}
		return current.getCount();
	}

}

class Node {

	private Node[] children;
	private int count;

	public Node(Node[] children, int count) {
		this.children = children;
		this.count = count;
	}

	public Node getChildrenItem(int i) {
		return children[i];
	}

	public void setChildrenItem(int i, Node node) {
		children[i] = node;
	}

	public int getCount() {
		return count;
	}

	public void setCount(int count) {
		this.count = count;
	}

}

程序二 HashMap类

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		Scanner scn = new Scanner(System.in);
		Map<String, Integer> map = new HashMap<String, Integer>();
		while (scn.hasNext()) {
			String word = scn.nextLine();
			if (0 == word.length()) {
				break;
			}
			for (int i = 1; i <= word.length(); ++i) {
				String substr = word.substring(0, i);
				if (map.containsKey(substr)) {
					map.put(substr, map.get(substr) + 1);
				} else {
					map.put(substr, 1);
				}
			}
		}
		while (scn.hasNext()) {
			String word = scn.nextLine();
			if (map.containsKey(word)) {
				System.out.println(map.get(word));
			} else {
				System.out.println("0");
			}
		}
	}

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值