Java program to check for string rotation

Examples:

 
Input :  s1 = "ABCD", s2 = "CDAB"
Output : True
String s1 is rotation of s2.

Input :  s1 = "ABAD", s2 = "ADAB"
Output : True

Input : s1 = ABCD, and s2 = ACBD 
Output : False

One simple solution is to look first occurrence of s1 in s2. for each match, check if remaining string matches circularly.

An efficient solution is to concatenate s1 with itself. s2 may be a rotation of s1 if and as long as it's a substring of the rotated string. In java we will either use string contains or indexOf to see for substring.

 

// Java program to check if two given strings are
// rotations of each other

class StringRotation {

	/* Function checks if passed strings (str1 and str2)
	are rotations of each other */
	static boolean areRotations(String str1, String str2)
	{
		// There lengths must be same and str2 must be
		// a substring of str1 concatenated with str1.
		return (str1.length() == str2.length()) &&
			((str1 + str1).contains(str2));
	}

	// Driver method
	public static void main(String[] args)
	{
		String str1 = "AACD";
		String str2 = "ACDA";

		if (areRotations(str1, str2))
			System.out.println("Yes");
		else
			System.out.printf("No");
	}
}

Output:

Yes

 

Submit Your Programming Assignment Details