Given a string s1 and a string s2, write a snippet to say whether s2 is a rotation of s1?
(eg given s1 = ABCD and s2 = CDAB, return true, given s1 = ABCD, and s2 = ACBD , return false)
Algorithm: areRotations(str1, str2)
1. Create a temp string and store concatenation of str1 to str1 in temp. temp = str1.str1 2. If str2 is a substring of temp then str1 and str2 are rotations of each other. Example: str1 = "ABACD" str2 = "CDABA" temp = str1.str1 = "ABACDABACD" Since str2 is a substring of temp, str1 and str2 are rotations of each other.
Strings are rotations of each other
Library Functions Used:
strstr finds a sub-string within a string.
Prototype: char * strstr(const char *s1, const char *s2);
See http://www.lix.polytechnique.fr/Labo/Leo.Liberti/public/computing/prog/c/C/MAN/strstr.htm for more details
strncat concatenate two strings
Prototype: char *strcat(char *dest, const char *src);
See http://www.lix.polytechnique.fr/Labo/Leo.Liberti/public/computing/prog/c/C/MAN/strcat.htm for more details
Time Complexity: Time complexity of this problem depends on the implementation of strstr function.
If implementation of strstr is done using KMP matcher then complexity of the above program is (-)(n1 + n2) where n1 and n2 are lengths of strings. KMP matcher takes (-)(n) time to find a substrng in a string of length n where length of substring is assumed to be smaller than the string.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Check if strings are rotations of each other or not | Set 2
- Program to check if two strings are same or not
- Number of strings which starts and ends with same character after rotations
- Minimum circular rotations to obtain a given numeric string by avoiding a set of given strings
- Check if two numbers are bit rotations of each other or not
- Check if all rows of a matrix are circular rotations of each other
- Meta Strings (Check if two strings can become same after a swap in one string)
- Check whether all the rotations of a given number is greater than or equal to the given number or not
- Check whether two strings can be made equal by reversing substring of equal length from both strings
- Check if two strings are k-anagrams or not
- Check whether two strings are anagram of each other
- Check if two strings are permutation of each other
- Check if two given strings are isomorphic to each other
- Check whether Strings are k distance apart or not
- Check if edit distance between two strings is one
- Check whether two strings are equivalent or not according to given condition
- Check if two strings have a common substring
- Check if there is any common character in two given strings
- Check if all the palindromic sub-strings are of odd length
- Check if two strings are same ignoring their cases