Check for string rotation in Java
Given two strings s1 and s2, write a snippet to check whether s2 is a rotation of s1. Strings may contain duplicates.
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 search first occurrence of s1 in s2. For every match, check if remaining string matches circularly.
An efficient solution is to concatenate s1 with itself. s2 is a rotation of s1 if and only if it is a substring of the rotated string. In java we can either use string contains or indexOf to check for substring.