Ray-Yan 2016-03-24 03:40 采纳率: 100%
浏览 1635
已采纳

求nextValue数组实现串模式匹配

如下代码:

 class KMP{
    public void getNext(char T[],int nextval[]){
        int i=1,j=0;
        nextval[1] = 0;
        while(i<T[0]){
            if(j==0||T[i]==T[j]){
                ++i;
                ++j;
                if(T[i]!=T[j]){  //Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException
                    nextval[i] = j;
                }else{
                    j = nextval[i];
                }
            }else{
                j = nextval[j];
            }
        }
    }
    public void kmp(char S[],char T[]){
        int i=0,j=0;
        int next[] = new int[80];
        getNext(T,next);
        for(;i<S.length&&j<T.length;){
            if(S[i]==T[j]){
                i++;
                j++;
            }else{
                j = next[j];
                if(j == -1){
                    i++;
                    j++;
                }
            }
        }
        if(j==T.length){
            System.out.println(i-T.length+1);               
        }else{
            System.out.println("匹配失败");
        }
    }
}
public class String_matching {
    public static void main(String[] args) {
        String str1 = "abababac";
        String str2 = "bac";
        char S[] = str1.toCharArray();
        char T[] = str2.toCharArray();
        KMP k = new KMP();
        k.kmp(S, T);
    }
}

通过求nextValue[ ]数组,实现串匹配,但运行出现数组越界异常,请帮忙看下正确的实现方法,谢谢!

  • 写回答

1条回答

  • 毕小宝 博客专家认证 2016-03-24 06:49
    关注

    你的getNext算法实现有问题,你的while(i<T[0])但实际上你的T[0]并不是存储的数组的长度的。
    给个正确版本的实现:http://blog.csdn.net/tkd03072010/article/details/6824326

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!