"Programmer Code Interview Guide" Chapter 5 Binary Tree Questions Determine whether two strings are revolving words

topic

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

java code

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));

    }
}

result

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324840097&siteId=291194637