How to check if a String is rotation of other in JAVA

 

There are many ways to check whether a String is rotation of another string or not. Here we will discuss two of them. The first one is the simple method using the string concatenation method and our second approach will be without using string concatenation.

1. Using String Concatenation Method :

i. We will first concatenate the first string with itself.

ii. Then we will check if the concatenated string contains the second string or not. It contains the second string a rotated version of the first string.

2. Without Using String Concatenation Method :

i. if any string is null then not possible else check the next step

ii. Check if the length of both strings is the same or not, If not then they are not rotation. If yes, then proceed to the next step.

iii. Check if both Strings are equal, if yes then s2 is a rotation of s1. If not, then move to the next step.

iv. Take the first character of the first string and find the index in the second string. If not found, then it's not the rotation, but if found, proceed to the next step.

v. Subtract the length of the rotated string with the index found to find the final position.

vi. Check if the first character of the rotated String is the same as the character at the final position of input String "AND" the input.substring(finalPos) is equal to the rotated.substring(0, index).

Post a Comment

0 Comments