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

题目

如果一个字符串str,把字符串str前面任意的部分挪到后面形成的字符串叫作str的旋转词。比如str="12345",str的旋转词有"12345","23451","34512","45123"和"51234"。给定两个字符串a和b,请判断a和b是否互为旋转词。

举例

a="cdab",b="abcd" 返回true

a="1ab2",b="ab12" 返回false

a="2ab1",b="ab12" 返回true

如果a和b长度不一样,那么a和b必然不互为旋转词,可以直接返回false。当a和b长度一样,都为N时,要求解法的时间复杂度为O(N).

如果a和b长度一样,先生成一个大字符串b2,b2是两个字符串b拼在一起的结果,即String b2 = b +b。

java 复制代码
public class KMP {

    public static boolean isRotation(String a, String b) {
        if(a == null || b == null || a.length() != b.length()){
            return false;
        }
        String b2 = b + b;
        return kmpSearch(b2, a) != -1;
    }

    public static int[] compteNext(String pattern) {
        int[] next = new int[pattern.length()];
        int j = 0;
        next[0] = j;
        for (int i = 1; i < pattern.length(); i++) {
            while (j > 0 && pattern.charAt(i)!= pattern.charAt(j)) {
                j = next[j - 1];
            }
            if (pattern.charAt(i) == pattern.charAt(j)) {
                j++;
            }
            next[i] = j;
        }
        return next;
    }

    public static int kmpSearch(String text, String pattern) {
        int[] next = compteNext(pattern);
        int i = 0, j = 0;
        while (i < text.length() && j < pattern.length()) {
            if (text.charAt(i) == pattern.charAt(j)) {
                i++;
                j++;
            } else if (j > 0) {
                j = next[j - 1];
            } else {
                i++;
            }
        }
        if (j == pattern.length()) {
            return i - j;
        } else {
            return -1;
        }
    }

    public static void main(String[] args) {
        String text = "cdab";
        String pattern = "abcd";
        System.out.println("Pattern found at : " + isRotation(text, pattern));
    }
}
相关推荐
骑着蜗牛撵大象3277 分钟前
大模型 Agent 的沙箱护栏:gVisor 隔离、出口白名单与审计闭环
java·开发语言·jvm·安全·agent沙箱·gvisor·microvm
独泪了无痕10 分钟前
Hutool之LocalDateTimeUtil:让时间间隔操作如虎添翼
java
三无少女指南2 小时前
从这里开始:Java 后端与 AI 工程的三条阅读路线
java·学习路线·ai工程
香蕉大香蕉(06敬畏市场)2 小时前
MySQL 单点详解(07)
java·数据库·mysql·ai·博客·八股
nice_lcj5202 小时前
深入理解 Java 反射:从 Class 对象到方法调用(含性能实测 + 迷你 IOC 实战 + 面试考点)
java·开发语言·后端·面试
骑着蜗牛撵大象3273 小时前
2026 后端 AI 工程化:Spring AI 管调用、MCP 管工具、Agent 内嵌管自治
java·人工智能·后端·spring·ai·可观测性·mcp
tryxr3 小时前
JVM 垃圾回收机制
java·jvm·gc·垃圾回收
吞下星星的少年·-·3 小时前
Div.3 CF 1131A题(排序,模拟)
算法·模拟·排序
揣一尾游鱼yu4 小时前
Spring上(IOC)笔记
java·笔记·spring·ioc