0
点赞
收藏
分享

微信扫一扫

KMP算法练习——IsRotation

guanguans 2022-03-30 阅读 25
package com.harrison.class16;

/**
 * @author Harrison
 * @create 2022-03-30-14:04
 * @motto 众里寻他千百度,蓦然回首,那人却在灯火阑珊处。
 */
public class Code02_IsRotation {
    public static boolean isRotation(String a,String b){
        if(a==null || b==null || a.length()!=b.length()){
            return false;
        }
        String b2=b+b;
        return getIndexOf(b2,a)!=-1;
    }

    public static int getIndexOf(String s1,String s2){
        if(s1.length()<s2.length()){
            return -1;
        }
        char[] str1=s1.toCharArray();
        char[] str2=s2.toCharArray();
        int[] next=getNextArray(str2);
        int x=0;
        int y=0;
        while(x<s1.length() && y<s2.length()){
            if(str1[x]==str2[y]){
                x++;
                y++;
            }else if(next[y]==-1){
                x++;
            }else{
                y=next[y];
            }
        }
        return y==s2.length()?x-y:-1;
    }

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

    public static void main(String[] args) {
        String str1 = "liaohongsi";
        String str2 = "hongsiliao";
        System.out.println(isRotation(str1, str2));
    }
}

举报

相关推荐

算法练习题31---KMP算法

KMP 算法

kmp 算法

【算法】KMP算法

【算法总结】KMP算法

KMP算法(转载)

0 条评论