Skip to content

Commit d30b19d

Browse files
committed
check rotation
1 parent 56d0b07 commit d30b19d

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed

DSA Crack Sheet/README.md

+1
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@
5959
- [Palindrome String](https://practice.geeksforgeeks.org/problems/palindrome-string0817/1 "view question") - [Cpp Solution](./solutions/Palindrome%20String.cpp)
6060
- [Print all the duplicates in the input string](https://www.geeksforgeeks.org/print-all-the-duplicates-in-the-input-string/ "view topic")
6161
- [Why strings are immutable in Java?](https://javarevisited.blogspot.com/2010/10/why-string-is-immutable-or-final-in-java.html#:~:text=The%20string%20is%20Immutable%20in,cached%20in%20the%20String%20pool.&text=Since%20Strings%20are%20very%20popular,which%20was%20stored%20in%20HashMap. "view topic")
62+
- [Check if strings are rotations of each other or not](https://practice.geeksforgeeks.org/problems/check-if-strings-are-rotations-of-each-other-or-not-1587115620/1# "view question") - [Cpp Solution](./solutions/Check%20if%20strings%20are%20rotations%20of%20each%20other%20or%20not.cpp)
6263
- []( "view question") - [Cpp Solution](./solutions/.cpp)
6364

6465
### Searching & Sorting
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
/*
2+
Check if strings are rotations of each other or not
3+
====================================================
4+
5+
Given two strings s1 and s2. The task is to check if s2 is a rotated version of the string s1. The characters in the strings are in lowercase.
6+
7+
Example 1:
8+
Input:
9+
geeksforgeeks
10+
forgeeksgeeks
11+
Output:
12+
1
13+
Explanation: s1 is geeksforgeeks, s2 is
14+
forgeeksgeeks. Clearly, s2 is a rotated
15+
version of s1 as s2 can be obtained by
16+
left-rotating s1 by 5 units.
17+
18+
Example 2:
19+
Input:
20+
mightandmagic
21+
andmagicmigth
22+
Output:
23+
0
24+
Explanation: Here with any amount of
25+
rotation s2 can't be obtained by s1.
26+
27+
Your Task:
28+
The task is to complete the function areRotations() which checks if the two strings are rotations of each other. The function returns true if string 1 can be obtained by rotating string 2, else it returns false.
29+
30+
Expected Time Complexity: O(N).
31+
Expected Space Complexity: O(N).
32+
Note: N = |s1|.
33+
34+
Constraints:
35+
1 <= |s1|, |s2| <= 107
36+
*/
37+
38+
/* Function to check if two strings are rotations of each other
39+
* s1, s2: are the input strings
40+
*/
41+
bool areRotations(string s1, string s2)
42+
{
43+
if (s1.size() != s2.size())
44+
return false;
45+
auto temp = s1 + s1;
46+
for (int i = 0; i < temp.size(); ++i)
47+
{
48+
if (temp[i] == s2[0] && temp.substr(i, s2.size()) == s2)
49+
return true;
50+
}
51+
return false;
52+
}

0 commit comments

Comments
 (0)