Given two strings, s1
and s2
, check if s1
and s2
are rotations of each other. The rotation is in the clockwise direction.
s1 = "helloeducative"
s2 = "educativehello"
Here, s2
is the rotated version of s1
.
The first condition to check is whether the two strings are of the same length. If the strings are of different lengths, then we can easily say the two strings are not rotations of each other.
The next steps of the algorithm are as follows:
In the image above, s1
is concatenated to itself and we can find s2
in the concatenated string of s1
.
public class Main{public static boolean check(String s1, String s2) {if (s1.length() != s2.length()) return false;String concatenatedString = s1 + s1;return concatenatedString.contains(s2);}public static void main(String[] args) {String s1 = "helloeducative";String s2 = "educativehello";boolean flag = check(s1, s2);if(flag) System.out.println(s1 + " and " + s2 + " are rotation of each other");else System.out.println(s1 + " and " + s2 + " are not rotation of each other");}}
Free Resources