字符串匹配算法

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;
 }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值