Check if a string can be obtained by rotating another string d places | C ++ implementation of the approach ; Function to reverse an array from left index to right index ( both inclusive ) ; Function that returns true if str1 can be made equal to str2 by rotating either d places to the left or to the right ; Left Rotation string will contain the string rotated Anti - Clockwise Right Rotation string will contain the string rotated Clockwise ; Copying the str1 string to left rotation string and right rotation string ; Rotating the string d positions to the left ; Rotating the string d positions to the right ; Compairing the rotated strings ; If cannot be made equal with left rotation ; If cannot be made equal with right rotation ; If both or any one of the rotations of str1 were equal to str2 ; Driver code ; d is the rotating factor ; In case length of str1 < d
#include <bits/stdc++.h> NEW_LINE using namespace std ; void ReverseArray ( string & arr , int left , int right ) { char temp ; while ( left < right ) { temp = arr [ left ] ; arr [ left ] = arr [ right ] ; arr [ right ] = temp ; left ++ ; right -- ; } } bool RotateAndCheck ( string & str1 , string & str2 , int d ) { if ( str1 . length ( ) != str2 . length ( ) ) return false ; string left_rot_str1 , right_rot_str1 ; bool left_flag = true , right_flag = true ; int str1_size = str1 . size ( ) ; for ( int i = 0 ; i < str1_size ; i ++ ) { left_rot_str1 . push_back ( str1 [ i ] ) ; right_rot_str1 . push_back ( str1 [ i ] ) ; } ReverseArray ( left_rot_str1 , 0 , d - 1 ) ; ReverseArray ( left_rot_str1 , d , str1_size - 1 ) ; ReverseArray ( left_rot_str1 , 0 , str1_size - 1 ) ; ReverseArray ( right_rot_str1 , 0 , str1_size - d - 1 ) ; ReverseArray ( right_rot_str1 , str1_size - d , str1_size - 1 ) ; ReverseArray ( right_rot_str1 , 0 , str1_size - 1 ) ; for ( int i = 0 ; i < str1_size ; i ++ ) { if ( left_rot_str1 [ i ] != str2 [ i ] ) { left_flag = false ; } if ( right_rot_str1 [ i ] != str2 [ i ] ) { right_flag = false ; } } if ( left_flag right_flag ) return true ; return false ; } int main ( ) { string str1 = " abcdefg " ; string str2 = " cdefgab " ; int d = 2 ; d = d % str1 . size ( ) ; if ( RotateAndCheck ( str1 , str2 , d ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }