diff --git a/src/main/java/com/thealgorithms/strings/StringRotation.java b/src/main/java/com/thealgorithms/strings/StringRotation.java new file mode 100644 index 000000000000..30a5725477a8 --- /dev/null +++ b/src/main/java/com/thealgorithms/strings/StringRotation.java @@ -0,0 +1,28 @@ +package com.thealgorithms.strings; + +public final class StringRotation { + + private StringRotation() { + throw new UnsupportedOperationException("Utility class"); + } + + /** + * Checks if str2 is a rotation of str1. + * + * @param str1 the original string + * @param str2 the string to check for rotation + * @return true if str2 is a rotation of str1, false otherwise + */ + public static boolean isRotation(String str1, String str2) { + if (str1 == null || str2 == null) { + return false; + } + + if (str1.length() != str2.length()) { + return false; + } + + String concatenated = str1 + str1; + return concatenated.contains(str2); + } +} diff --git a/src/test/java/com/thealgorithms/strings/StringRotationTest.java b/src/test/java/com/thealgorithms/strings/StringRotationTest.java new file mode 100644 index 000000000000..b76df428277c --- /dev/null +++ b/src/test/java/com/thealgorithms/strings/StringRotationTest.java @@ -0,0 +1,30 @@ +package com.thealgorithms.strings; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; + +public class StringRotationTest { + + @Test + void testValidRotation() { + assertTrue(StringRotation.isRotation("waterbottle", "erbottlewat")); + } + + @Test + void testInvalidRotation() { + assertFalse(StringRotation.isRotation("hello", "world")); + } + + @Test + void testDifferentLengths() { + assertFalse(StringRotation.isRotation("abc", "abcd")); + } + + @Test + void testNullInput() { + assertFalse(StringRotation.isRotation(null, "abc")); + assertFalse(StringRotation.isRotation("abc", null)); + } +}