Skip to content

Commit 279a307

Browse files
feat(strings): add StringRotation to check if one string is a rotation of another
Signed-off-by: konduri-lakshmi-prasanna <konduriprasanna22@gmail.com>
1 parent 14a23b7 commit 279a307

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package com.thealgorithms.strings;
2+
3+
import java.util.Scanner;
4+
5+
public class StringRotation {
6+
7+
/**
8+
* Checks if str2 is a rotation of str1
9+
* @param str1 Original string
10+
* @param str2 String to check for rotation
11+
* @return true if str2 is a rotation of str1, false otherwise
12+
*/
13+
public static boolean isRotation(String str1, String str2) {
14+
if (str1 == null || str2 == null) {
15+
return false;
16+
}
17+
18+
if (str1.length() != str2.length()) {
19+
return false;
20+
}
21+
22+
String concatenated = str1 + str1;
23+
return concatenated.contains(str2);
24+
}
25+
26+
public static void main(String[] args) {
27+
Scanner scanner = new Scanner(System.in);
28+
29+
System.out.print("Enter first string: ");
30+
String str1 = scanner.nextLine();
31+
32+
System.out.print("Enter second string: ");
33+
String str2 = scanner.nextLine();
34+
35+
boolean result = isRotation(str1, str2);
36+
37+
if (result) {
38+
System.out.println("\"" + str2 + "\" is a rotation of \"" + str1 + "\".");
39+
} else {
40+
System.out.println("\"" + str2 + "\" is NOT a rotation of \"" + str1 + "\".");
41+
}
42+
43+
scanner.close();
44+
}
45+
}

0 commit comments

Comments
 (0)