AC自动机算法JAVA

AC算法

fail指针

字典树

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

public class Didi {
    private static Node root=new Node();
    private static Queue<Node> queue=new LinkedList<Node>();
    public static void main(String[] args) {
        Scanner input=new Scanner(System.in);
        String[] word={"say","she","shr","he","her"};
        String s="yasherhs";
        for (int i = 0; i < word.length; i++) {
            insert(word[i]);
        }
        build_ac_automation(root);
        System.out.println(query(s));
    }

    public static int query(String s){
        int count=0;
        Node p=root;
        char[] str=s.toCharArray();
        for (int i = 0; i < str.length; i++) {
            int index=str[i]-'a';
            while(p.child[index]==null&&p!=root){
                p=p.fail;
            }
            p=p.child[index];
            p=(p==null)?root:p;
            Node temp=p;
            while(temp!=root&&temp.count!=-1){
                count+=temp.count;
                temp.count=-1;
                temp=temp.fail;
            }
        }
        return count;
    }
    public static void build_ac_automation(Node root){

        root.fail=null;
        queue.add(root);
        while(!queue.isEmpty()){
            Node temp=queue.poll();
            Node p=null;
            for (int i = 0; i < 26; i++) {
                if(temp.child[i]!=null){
                    if(temp==root){
                        temp.child[i].fail=root;
                    }else{
                        p=temp.fail;
                        while(p!=null){
                            if(p.child[i]!=null){
                                temp.child[i].fail=p.child[i];
                                break;
                            }
                            p=p.fail;
                        }
                        if(p==null){
                            temp.child[i].fail=root;
                        }
                    }
                    queue.add(temp.child[i]);   
                }
            }
        }
    }
    public static void insert(String str){
        if(str.isEmpty()||str==""){
            return;
        }
        Node cnode=root;
        for (int i = 0; i < str.length(); i++) {
            int index=str.charAt(i)-'a';
            if(cnode.child[index]==null){
                Node pnode=new Node();
                cnode.child[index]=pnode;
            }
            cnode=cnode.child[index];
        }
        cnode.count=1;
    }
}

class Node{
    int count;
    Node fail;
    Node[] child;
    public Node(){
        fail=null;
        count=0;
        child=new Node[26];
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值