判斷兩個字符串是否爲旋轉詞(KMP算法)

題目:

思路:

這個題首先需要判斷兩個字符串的長度,如果長度不相等的話直接返回false.接着創造一個新的字符串b1,是的b1=b+b。接着判斷在新的字符串b1中是否包含有字符串a,這裏使用的是KMP算法。這個算法我還不太懂。。。。先把左神的相關代碼都寫在下面。整個算法的時間複雜度是o(n),n是a,b字符串的長度。

這個下午清醒了看。。。。。這個還是有點不理解。。。。

代碼:

import java.util.*;
public class zcy1 {
    public static void main(String[]args){
        Scanner sc=new Scanner(System.in);
        String a=sc.next();
        String b=sc.next();

        if( (a.length()!=b.length())){
            System.out.println(false);
        }
        else{
            String b1=b+b;
//如果b1中含有字符串a,返回在b1中的下標
           int index=getIndex(b1,a);
           System.out.println(index!=-1);
        }



    }
    public static int getIndex(String s,String m){
//其中s是大的字符串,,m是比較小的那個字符串
        if(s==null||m==null||m.length()<1||s.length()<m.length()){
            return -1;
        }
        char[]ss=s.toCharArray();
        char[]ms=m.toCharArray();
        int si=0;
        int mi=0;
//創建ms對應的next數組
        int[]next=getNextArray(ms);
        while(si<ss.length&&mi<ms.length){
            if(ss[si]==ms[mi]){
                si++;
                mi++;
            }
            else if(next[mi]==-1){
                si++;
            }
            else{
                mi=next[mi];
            }
        }
        return mi==ms.length?si-mi:-1;
    }

    public static int[] getNextArray(char[]ms){
        if(ms.length==1){
            return new int[]{-1};
        }
        int []next=new int [ms.length];
        next[0]=-1;
        next[1]=0;
        int pos=2;
        int cn=0;
        while(pos<next.length){
            if(ms[pos-1]==ms[cn]){
                next[pos++]=++cn;
            }
            else if(cn>0){
                cn=next[cn];
            }
            else{
                next[pos++]=0;
            }
        }
        return next;
    }
    
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章