字符串问题----判断两个字符串是否互为旋转词

判断两个字符串是否互为旋转词

  

  如果一个字符串str,把字符串str前面的任意部分挪到后面形成的字符串叫做str的旋转词。给定两个字符串,判断是否互为旋转词。比如 a="abcd",b="cdab",true a="abcd",b="bcad",false

  

  【解题思路】

  如果长度不一样,肯定是false,如果长度一样,时间复杂度是O(N)。

  方法一:直接利用String的contains 方法

  方法二:看contains方法的源码,套用它的源码的方法

package com.test;

/**
 * Created by Demrystv.
 */
public class isRotation {


    /**
     * 方法一:直接利用String的contains 方法
     * @param a
     * @param b
     * @return
     */
    /*
    如果a 和b 的长度一样长,先生成一个大字符串b2, b2=b+b,即b2就是两个b 拼接起来的,然后看b2 中是否包含a,
    如果包含a, 说明a 和b 互为旋转词, 如果不包含,说明不是互为旋转词。
     */
    public boolean isRotation1(String a, String b){
        if (a == null || b == null || a.length() != b.length()){
            return false;
        }
        String b2 = b + b;
        return b2.contains(a);// 可以看其底层实现过程
    }


    /**
     * 方法二:看contains方法的源码,套用它的源码的方法
     * @param a
     * @param b
     * @return
     */

    public boolean isRotation2(String a, String b){
        if (a == null || b == null || a.length() != b.length()){
            return false;
        }
        String b2 = b + b;
        return indexOf(b2, a, 0) > -1;
    }

    private int indexOf(String b2, String a, int index){
        char[] source = b2.toCharArray();
        char[] target = a.toCharArray();
        return func(source, 0, source.length, target, 0, target.length, index);
    }

    private int func(char[] source, int sourceOffset, int sourceCount,
                        char[] target, int targetOffset, int targetCount,
                        int fromIndex) {
        if (fromIndex >= sourceCount) {
            return (targetCount == 0 ? sourceCount : -1);
        }
        if (fromIndex < 0) {
            fromIndex = 0;
        }
        if (targetCount == 0) {
            return fromIndex;
        }

        char first = target[targetOffset];
        int max = sourceOffset + (sourceCount - targetCount);

        for (int i = sourceOffset + fromIndex; i <= max; i++) {
            if (source[i] != first) {
                while (++i <= max && source[i] != first);
            }

            if (i <= max) {
                int j = i + 1;
                int end = j + targetCount - 1;
                for (int k = targetOffset + 1; j < end && source[j]
                        == target[k]; j++, k++);

                if (j == end) {
                    return i - sourceOffset;
                }
            }
        }
        return -1;
    }

}

猜你喜欢

转载自www.cnblogs.com/Demrystv/p/9557641.html
今日推荐