字符串匹配算法

来源:互联网 发布:linux进程间通信 编辑:程序博客网 时间:2024/04/25 22:58

kmp算法:(java版)
class SuiteString{
    /**
     * To get the NEXT array coordinate the subString.
     * @param sub the subString
     * @return the NEXT array
     * */
 private static int[] getNext( String sub){
     final int subLength = sub.length();  //length of sub string
     int[] next = new int[ subLength+1 ];
     int i = 1, j = 0; // i: sub's index;    j: the value of next[i]
     next[0] = 0;
     next[1] = 0;
     /* In fact, the operation is end of 'i == subLength+1' */
     while ( i < subLength ){
         if ( sub.charAt(i) == sub.charAt(j)){
             ++i; ++j;
             next[i] = j;
         }
         else{
             /* if 'j == 0' and sub[i] != sub[j] then 'next[++i] == 0'*/
             if ( j == 0)
              next[++i] = j;
             else
                 j = next[j];
         }
     }

     return next;
 }
 /**
     * Search the position of sub string in major string from specified position.
     * @param str the major string
     * @param sub the sub string
     * @param index the specified position
     * @return the position searched out, If return -1 reference search failed.
     * */
    public static int indexof( String str, String sub, int index){
        /* if str or sub is null or space string return failed*/
        if ( str == null || str == ""
            || sub == null || sub == "")
            return -1;
       
     int[] next = getNext( sub);
     int i = index, j = 0; //i: str's index;    j: sub's index
     final int strLength = str.length();
     final int subLength = sub.length();
     while( i < strLength && j < subLength){
         if ( str.charAt(i) == sub.charAt(j) ){
             ++i; ++j;
         }
         else{
             if ( j == 0)
                 ++i;            
             else
                 j = next[j];
         }
     }
    
     if ( j == subLength)
         return i - subLength;
     return -1;
 }
}

原创粉丝点击