5. Check whether one string is a rotation of another
5. Check whether one string is a rotation of another
Problem link :- click here
package programs;
public class String__5
{
static Boolean areRotations(String s1, String s2)
{
if( s1.length() != s2.length() )
return false;
//method 1
/*
String concatenate = s1 + s1;
if( concatenate.indexOf(s2) != -1 )
return true;
return false;
*/
//method 2
/*
we will find the index of first character of s2 in s1
using that index we will check if s2 is the rotation of s1
*/
char x = s2.charAt(0); //first character
int index = 0; //index of first character
for(int i=0; i<s1.length(); i++)
{
if(s1.charAt(i) == x)
{
index = i;
break; //because one step process
}
}
for(int i=0; i<s1.length(); i++)
{
if( s1.charAt(i) != s2.charAt(index) )
return false;
index = (index+1) % s1.length();
}
return true;
}
public static void main(String[] args)
{
String s1 = "ABCD";
String s2 = "CDMB";
Boolean ans = areRotations(s1, s2);
if(ans)
System.out.println("s2 is rotation of s1");
else
System.out.println("s2 is not rotation of s1");
}
}
Time complexity :- O(n)
Space complexity :- O(1)
Comments
Post a Comment