您的位置:首页 > 编程语言 > Java开发

ACM HDOJ 2222 (Keywords Search)

2014-01-19 22:38 381 查看
题目链接 http://acm.hdu.edu.cn/showproblem.php?pid=2222

import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

public class Main {

public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int casesNumber = Integer.parseInt(scn.next());
while (0 <= --casesNumber) {
Trie trie = new Trie();
int wordsNumber = Integer.parseInt(scn.next());
while (0 <= --wordsNumber) {
trie.insert(scn.next());
}
trie.build();
System.out.println(trie.search(scn.next()));
}
scn.close();
}

}

class Trie {

private Node root;

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

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

public void build() {
Queue<Node> queue = new LinkedList<Node>();
queue.offer(root);
while (!queue.isEmpty()) {
Node current = queue.poll();
for (int i = 0; i < 26; ++i) {
if (null != current.getChildrenItem(i)) {
if (current == root) {
current.getChildrenItem(i).setFail(root);
} else {
Node fail = current.getFail();
while (null != fail) {
if (null != fail.getChildrenItem(i)) {
current.getChildrenItem(i).setFail(
fail.getChildrenItem(i));
break;
}
fail = fail.getFail();
}
if (null == fail) {
current.getChildrenItem(i).setFail(root);
}
}
queue.offer(current.getChildrenItem(i));
}
}
}
}

public int search(String str) {
int count = 0;
Node current = root;
for (int i = 0; i < str.length(); ++i) {
int index = str.charAt(i) - 'a';
while (null == current.getChildrenItem(index) && current != root) {
current = current.getFail();
}
current = current.getChildrenItem(index);
if (null == current) {
current = root;
}
Node end = current;
while (end != root) {
if (-1 != end.getCount()) {
count += end.getCount();
end.setCount(-1);
}
end = end.getFail();
}
}
return count;
}

}

class Node {

private Node[] children;
private Node fail;
private int count;

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

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

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

public Node getFail() {
return fail;
}

public void setFail(Node fail) {
this.fail = fail;
}

public int getCount() {
return count;
}

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

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ACM HDOJ 2222 JAVA