Check if strings are rotations of each other or not | Set 2 | Java program to check if two strings are rotations of each other . ; create lps [ ] that will hold the longest prefix suffix values for pattern ; length of the previous longest prefix suffix ; lps [ 0 ] is always 0 ; the loop calculates lps [ i ] for i = 1 to n - 1 ; match from that rotating point ; Driver code
import java . util . * ; import java . lang . * ; import java . io . * ; class stringMatching { public static boolean isRotation ( String a , String b ) { int n = a . length ( ) ; int m = b . length ( ) ; if ( n != m ) return false ; int lps [ ] = new int [ n ] ; int len = 0 ; int i = 1 ; lps [ 0 ] = 0 ; while ( i < n ) { if ( a . charAt ( i ) == b . charAt ( len ) ) { lps [ i ] = ++ len ; ++ i ; } else { if ( len == 0 ) { lps [ i ] = 0 ; ++ i ; } else { len = lps [ len - 1 ] ; } } } i = 0 ; for ( int k = lps [ n - 1 ] ; k < m ; ++ k ) { if ( b . charAt ( k ) != a . charAt ( i ++ ) ) return false ; } return true ; } public static void main ( String [ ] args ) { String s1 = " ABACD " ; String s2 = " CDABA " ; System . out . println ( isRotation ( s1 , s2 ) ? "1" : "0" ) ; } }