Tuesday, February 24, 2009

Given a string s1 and a string s2, write a snippet to say whether s2 is a rotation of s1 using only one call to strstr routine?

(eg given s1 = ABCD and s2 = CDAB, return true)
(given s1 = ABCD, and s2 = ACBD , return false)

Sol:
This is most frequently asked question. It can be solved with simple logic as given below.

1 . Check if both s1, s2 are of same length.
2. if( strstr(strcat(s1,s1), s2) !=NULL) return TRUE
else
return FALSE

Example:
if s1 = ABCD, the concatination will make it ABCDABCD and hence any rotation will fall within the concatenated string. s2 is italicized in conctenized in above concatenated string.