public class TwoTimesACharm {
public static void main(String[] args)
{
String[] test1 = {"1234", "4123", "3412", "2341", "1212", "12345678"};
String original = "1234";
TwoTimesACharm aCharm = new TwoTimesACharm();
for(String s:test1)
{
System.out.println("It is " + aCharm.isRotation(original, s) + " that " + s + " is a rotation of " + original);
}
System.out.println("\n Second method test. the first method implementation doesnt show any skills");
for(String s:test1)
{
System.out.println("It is " + aCharm.isRotation2(original, s) + " that " + s + " is a rotation of " + original);
}
}
//so the reason that we repeat the original string twice is because the rotation would be in the string.
//for example string "1234" possible rotations are
//shift right 4123, 3412, 2341
//shift left 2341, 3412, 4123
// repeat original string "12341234" we will see those rotations are present in there.
private boolean isRotation(String originalString, String rotateString)
{
String repeatTwice = originalString+originalString;
return (repeatTwice.indexOf(rotateString) > -1 ? true:false);
}
private boolean isRotation2(String originalString, String rotateString)
{
//before going any further make sure they are the same length.
if(originalString.length() != rotateString.length())
return false;
//make sure that the inputs aren't the same.
if(originalString.equals(rotateString))
return true;
//I would use StringBuilder for efficiency but for simplicity I used a string
String repeatTwice = originalString+originalString;
int i = 0;
// we do the length of the string because the start of i in the repeatTwice string shouldn't be
//pass the end of the original string or else we will get array out of bounds.
while(i <= originalString.length())
{
//so basically we are iterating through the repeat string until we find a match.
if(rotateString.equals(repeatTwice.substring(i, i+originalString.length())))
return true;
else
i++;
}
return false;
}
}