编程之美--字符串循环移位包含问题

package structure;

import java.util.Arrays;

/**
 * 
 * 字符串移位包含问题 问题:string a = "aabcd" ,string b = "cdaa" 判断将 a 字符串通过循环移位能否包含 串 b
 *  解法1:对 a 进行每次移位,然后再与 b 进行包含判断,这里利用KMP 进行匹配处理 解法2:a 的循环移位一定是 aa 的子串,如果 b 可以被 a
 * 的循环移位串包含,那么  b 一定是 aa 的子串
 */
public class StringSiftCompare {

    public static void execute(String a, String b) {
	char[] s1 = a.toCharArray();
	char[] s2 = b.toCharArray();
	int[] next = next(s2);
	for (int i = 0, len = s1.length; i < len; i++) {
	    int ans = kmp(s1, s2, next);
	    if (ans != -1) {
		System.out.println("Yes");
		return;
	    }
	    leftSift(s1);
	}
	System.out.println("No");
    }

    /**
     * 多次匹配,没必要把 next 方法写在 kmp 中
     */
    static int kmp(char[] s1, char[] s2, int[] next) {
	int j = 0;
	for (int i = 0, len = s1.length; i < len; i++) {
	    while (j >= 0 && s1[i] != s2[j]) {
		j = next[j];
	    }
	    if (j < 0)
		j = 0;
	    else
		j++;
	    if (j == s2.length)
		return i - j + 1;
	}
	return -1;
    }

    static int[] next(char[] s) {
	int len = s.length;
	int[] next = new int[len];
	next[0] = -1;
	for (int i = 1; i < len; i++) { // 求 next[i],next[i] = next[i-1]+1
	    int j = i - 1;
	    while (j >= 0 && s[next[j] + 1] != s[i]) {
		j = next[j];
	    }
	    if (j >= 0)
		next[i] = next[j] + 1;
	    else
		next[i] = -1;
	}
	return next;
    }

    static void leftSift(char[] s) {
	int last = s.length - 1;
	char t = s[last];
	System.arraycopy(s, 0, s, 1, last - 1);
	s[0] = t;
    }

    static void execute2(String a, String b) {
	a = a + a;
	int ans = a.indexOf(b);
	System.out.println(ans >= 0 ? "Yes" : "No");
    }

    public static void main(String args[]) {
	String a = "AABCD", b = "BCD";
	//execute(a, b);
	execute2(a,b);

    }
}
    原文作者:BOY
    原文地址: https://blog.csdn.net/jiang_bing/article/details/8107954
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞