ACM HDOJ 1251 (统计难题 )

来源:互联网 发布:dbc数据库详解 编辑:程序博客网 时间:2024/05/17 08:13

题目链接 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 0
原创粉丝点击