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.
# include <bits/stdc++.h>
using
namespace
std;
bool
areRotations(string str1, string str2)
{
if
(str1.length() != str2.length())
return
false
;
string temp = str1 + str1;
return
(temp.find(str2) != string::npos);
}
int
main()
{
string str1 =
"AACD"
, str2 =
"ACDA"
;
if
(areRotations(str1, str2))
printf
(
"Strings are rotations of each other"
);
else
printf
(
"Strings are not rotations of each other"
);
return
0;
}
class
StringRotation
{
static
boolean
areRotations(String str1, String str2)
{
return
(str1.length() == str2.length()) &&
((str1 + str1).indexOf(str2) != -
1
);
}
public
static
void
main (String[] args)
{
String str1 =
"AACD"
;
String str2 =
"ACDA"
;
if
(areRotations(str1, str2))
System.out.println(
"Strings are rotations of each other"
);
else
System.out.printf(
"Strings are not rotations of each other"
);
}
}
def
areRotations(string1, string2):
size1
=
len
(string1)
size2
=
len
(string2)
temp
=
''
if
size1 !
=
size2:
return
0
temp
=
string1
+
string1
if
(temp.count(string2)>
0
):
return
1
else
:
return
0
string1
=
"AACD"
string2
=
"ACDA"
if
areRotations(string1, string2):
print
"Strings are rotations of each other"
else
:
print
"Strings are not rotations of each other"
Comments
Post a Comment