题目自己上杭电ACM网站上查,百度一搜就出来了。1004号题目比较简单,本人为了熟练一下JAVA特地写了2个数据结构,浪费了一些时间,其实JAVA类库中自带有,大家可以自己调用这样更方便。
AC的版本如下:
import java.util.Scanner; public class Main{ public static void main(String[] args) { IO io = new IO(); while (!io.inputValue()) { io.addToHashTab(); } io.printAnswer(); } } class IO{ private Scanner scan; private String[] buffer; private int num; private static Link answerLink; public IO(){ answerLink = new Link(); scan = new Scanner(System.in); } public boolean inputValue(){ num = scan.nextInt(); boolean isEnd = false; if(num != 0) { buffer = new String[num]; for(;num > 0; num --) { buffer[num-1] = scan.next(); } }else{ isEnd = true; } return isEnd; } public void addToHashTab() { HashTab ht = new HashTab(); for(int i = 0; i < buffer.length; i ++) { ht.addNode(buffer[i]); } answerLink.addNode(ht.getPopular()); } public void printAll(){ for(int i = 0; i < buffer.length; i ++){ System.out.println(buffer[i]); } } public void printAnswer(){ answerLink.print(); } } class HashTab { class Node{ private int times; private Node[] next; public Node(){ next = new Node[26]; times = 0; } public int getTimes() { return times; } public void setTimes(int times) { this.times = times; } public void addTimes(){ this.times ++; } public int add(char[] result,Node now){ for(int i = 0; i < result.length; i ++){ int value = result[i] - 97; if (now.next[value] == null) { Node newNode = new Node(); now.next[value] = newNode; } now = now.next[value]; } now.addTimes(); return now.getTimes(); } } private Node head; private String popular; private int maxTimes; public int getMaxTimes() { return maxTimes; } public void setMaxTimes(int maxTimes) { this.maxTimes = maxTimes; } public String getPopular() { return popular; } public void setPopular(String popular) { this.popular = popular; } public HashTab(){ head = new Node() ; popular = null; maxTimes = 0; } public void addNode(String word){ char[] result = word.toCharArray(); int times = head.add(result,head); if(times >= maxTimes){ this.setMaxTimes(times); this.setPopular(word); } } } class Link{ class Node{ private String popupar; private Node next; public Node(){ this.setPopupar(null); } public Node(String popular){ this.setPopupar(popular); } public Node getNext() { return next; } public void setNext(Node next) { this.next = next; } public String getPopupar() { return popupar; } public void setPopupar(String popupar) { this.popupar = popupar; } public void add(Node newNode) { if(this.getNext() == null){ this.setNext(newNode); }else{ this.getNext().add(newNode); } } } private Node head; public Link(){ head = null; } public void addNode(String popular){ Node newNode = new Node(popular); if(head == null){ head = newNode; }else{ head.add(newNode); } } public void print(){ Node now = head; while(now.getPopupar() != null) { System.out.println(now.getPopupar()); if(now.getNext() != null){ now = now.getNext(); }else{ break; } } } }大家如果有更好的见解可以留言嘛。