KMP算法的JAVA实现

package kmp;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class KMP {
    
    /*
     * 计算key的部分匹配表
     */
    private static Map<String,Integer>getPartialMatchTable(String str)
    {
        Map<String,Integer> result = new HashMap<String,Integer>();
        
        int length = str.length();
        
        for(int i = 1; i<=length; i++)
        {
            String partial = str.substring(0, i);
            
            int value = KMP.getPartialValue(partial);
            
            result.put(partial, value);    
        }
        return result;
    }
    
    /*
     * 计算string的部分匹配值
     */
    private static int getPartialValue(String str)
    {
        int result =0;
        
        int length = str.length();
        
        for(int i =1; i<length; i++)
        {
            if( str.substring(0,i).equals(str.substring(length-i, length)))
                result = i;
        }
        
        return result;
    }
    
    public static ArrayList<Integer> kmp(String searchString,String key)
    {
        ArrayList<Integer> result = new ArrayList<Integer>();
        
        Map<String,Integer> partialMatchTable = KMP.getPartialMatchTable(key);
        
        int length = searchString.length();
        
        int step =1;
        
        for(int i = 0; i < length; i = i+step)            
        {
            for(int j = 0; j < key.length(); j ++)
            {
                if(searchString.charAt(i+j) == key.charAt(j))
                {
                    if(j == key.length()-1)
                    {
                        //如果匹配正确记录下来并step 赋值为1
                        result.add(i);
                        
                        step = 1;
                    }
                }else{
                    //step = 已匹配的值-部分匹配值
                    step = j - partialMatchTable.get(key.substring(0, j+1));
                    
                    if(step == 0)
                    {
                        step =1;
                    }
                    break;
                }
            }
        }
        
        
        return result;
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        
        String temp = "ABCABC";
        
        String search = "ABABCABCHSIIAABCABCHSJDKAABCABCH";
        
        ArrayList<Integer> result = KMP.kmp(search, temp);
        
        for(Integer i:result )
        {
            System.out.println(i);
        }

    }

}

 

posted @ 2013-12-27 15:34  SunkSky  阅读(360)  评论(0编辑  收藏  举报