📌  相关文章
📜  检查字符串是否相互旋转的Java程序|设置 2(1)

📅  最后修改于: 2023-12-03 15:40:33.666000             🧑  作者: Mango

检查字符串是否相互旋转的Java程序

如果有两个字符串,我们需要判断它们是否相互旋转。例如,我们有字符串 s1 = "abcde"s2 = "cdeab",那么这两个字符串是相互旋转的。

public class CheckStringRotation {

    public static boolean isRotation(String s1, String s2) {
        if (s1.length() != s2.length()) {
            return false;
        }
        String s1s1 = s1 + s1;

        return s1s1.contains(s2);
    }

    public static void main(String[] args) {
        String s1 = "abcde";
        String s2 = "cdeab";
        System.out.println("Are " + s1 + " and " + s2 + " rotation of each other? " + isRotation(s1, s2));
    }
}
代码解析

这个程序通过 s1s2 两个字符串的长度来判断它们是否相互旋转。如果长度不等,则直接返回 false。否则,我们把 s1 重复一遍接在原字符串的后面,形成 s1s1

然后我们判断 s1s1 中是否包含 s2。如果包含,那么说明 s1s2 是相互旋转的。

示例
String s3 = "hello";
String s4 = "lohel";
System.out.println("Are " + s3 + " and " + s4 + " rotation of each other? " + isRotation(s3, s4));

输出结果为:

Are hello and lohel rotation of each other? true
总结

通过以上的演示,我们了解到了如何检查两个字符串是否相互旋转。这种方法很简单,不需要开辟额外的空间,而且时间复杂度为 $O(n)$。