《程序员代码面试指南》第五章 字符串问题 判断两个字符串是否互为旋转词

题目

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

java代码

package com.lizhouwei.chapter5;

/**
 * @Description: 判断两个字符串是否互为旋转词
 * @Author: lizhouwei
 * @CreateDate: 2018/4/23 21:59
 * @Modify by:
 * @ModifyDate:
 */
public class Chapter5_4 {
    public boolean isRotation(String str1, String str2) {
        if (str1 == null || str2 == null || str1.length() != str2.length()) {
            return false;
        }
        String str = str1 + str2;
        //KMP
        return str.contains(str1);
    }

    //测试
    public static void main(String[] args) {
        Chapter5_4 chapter = new Chapter5_4();
        String str1 = "cdab";
        String str2 = "abcd";
        String str3 = "abcde";

        System.out.println("cdab和abcd是否互为旋转词:" + chapter.isRotation(str1, str2));
        System.out.println("cdab和abcde是否互为旋转词:" + chapter.isRotation(str1, str3));

    }
}

结果

posted @ 2018-04-23 22:08  lizhouwei  阅读(200)  评论(0编辑  收藏  举报