Skip to content
Open
28 changes: 28 additions & 0 deletions src/main/java/com/thealgorithms/strings/StringRotation.java
Original file line number Diff line number Diff line change
@@ -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);
}
}
30 changes: 30 additions & 0 deletions src/test/java/com/thealgorithms/strings/StringRotationTest.java
Original file line number Diff line number Diff line change
@@ -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));
}
}