Given a string s1 and a string s2, write a function to check whether s2 is a rotation of s1 or not ?
If s2 is a rotation of s1 , return true otherwise its return false.
Steps to follow:
1) We have two strings ,s1 = ABCD and s2 = CDAB and we will create a variable concate which
store concatenation of s1 to s1.
String concate = s1.s1 ;
2) If s2 is a substring of concate variable then s1 and s2 are rotations of each other.
Example:
String s1 = "ABCD" ;
String s2 = "CDAB" ;
String concate = s1.s1 = "ABCDCDAB" ;
Since s2 is a substring of concate, and s1 and s2 are rotations of each other.
Example – Program to Check if strings are rotations of each other or not
public class StringRotation {
static boolean checkRotations(String str1, String str2) {
return (str1.length() == str2.length()) && ((str1 + str1).indexOf(str2) != -1);
}
public static void main(String[] args) {
String str1 = "ABCD";
String str2 = "CDAB";
if (checkRotations(str1, str2)) {
System.out.println("Strings are rotations of each other");
} else {
System.out.printf("Strings are not rotations of each other");
}
}
}
Output
Strings are rotations of each other