检查字符串是否相互旋转的程序
给定一个字符串s1 和一个字符串s2,写一个片段来说明 s2 是否是 s1 的旋转?
(例如,给定 s1 = ABCD 和 s2 = CDAB,返回真,给定 s1 = ABCD,和 s2 = ACBD,返回假)
算法: 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.
C++
// C++ program to check if two given strings
// are rotations of each other
# include
using namespace std;
/* Function checks if passed strings (str1
and str2) are rotations of each other */
bool areRotations(string str1, string str2)
{
/* Check if sizes of two strings are same */
if (str1.length() != str2.length())
return false;
string temp = str1 + str1;
return (temp.find(str2) != string::npos);
}
/* Driver program to test areRotations */
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;
}
C
// C program to check if two given strings are rotations of
// each other
# include
# include
# include
/* Function checks if passed strings (str1 and str2)
are rotations of each other */
int areRotations(char *str1, char *str2)
{
int size1 = strlen(str1);
int size2 = strlen(str2);
char *temp;
void *ptr;
/* Check if sizes of two strings are same */
if (size1 != size2)
return 0;
/* Create a temp string with value str1.str1 */
temp = (char *)malloc(sizeof(char)*(size1*2 + 1));
temp[0] = '';
strcat(temp, str1);
strcat(temp, str1);
/* Now check if str2 is a substring of temp */
ptr = strstr(temp, str2);
free(temp); // Free dynamically allocated memory
/* strstr returns NULL if the second string is NOT a
substring of first string */
if (ptr != NULL)
return 1;
else
return 0;
}
/* Driver program to test areRotations */
int main()
{
char *str1 = "AACD";
char *str2 = "ACDA";
if (areRotations(str1, str2))
printf("Strings are rotations of each other");
else
printf("Strings are not rotations of each other");
getchar();
return 0;
}
Java
// Java program to check if two given strings are rotations of
// each other
class StringRotation
{
/* Function checks if passed strings (str1 and str2)
are rotations of each other */
static boolean areRotations(String str1, String str2)
{
// There lengths must be same and str2 must be
// a substring of str1 concatenated with str1.
return (str1.length() == str2.length()) &&
((str1 + str1).indexOf(str2) != -1);
}
// Driver method
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");
}
}
// This code is contributed by munjal
Python3
# Python program to check if strings are rotations of
# each other or not
# Function checks if passed strings (str1 and str2)
# are rotations of each other
def areRotations(string1, string2):
size1 = len(string1)
size2 = len(string2)
temp = ''
# Check if sizes of two strings are same
if size1 != size2:
return 0
# Create a temp string with value str1.str1
temp = string1 + string1
# Now check if str2 is a substring of temp
# string.count returns the number of occurrences of
# the second string in temp
if (temp.count(string2)> 0):
return 1
else:
return 0
# Driver program to test the above function
string1 = "AACD"
string2 = "ACDA"
if areRotations(string1, string2):
print ("Strings are rotations of each other")
else:
print ("Strings are not rotations of each other")
# This code is contributed by Bhavya Jain
C#
// C# program to check if two given strings
// are rotations of each other
using System;
class GFG {
/* Function checks if passed strings
(str1 and str2) are rotations of
each other */
static bool areRotations(String str1,
String str2)
{
// There lengths must be same and
// str2 must be a substring of
// str1 concatenated with str1.
return (str1.Length == str2.Length )
&& ((str1 + str1).IndexOf(str2)
!= -1);
}
// Driver method
public static void Main ()
{
String str1 = "FGABCDE";
String str2 = "ABCDEFG";
if (areRotations(str1, str2))
Console.Write("Strings are"
+ " rotation s of each other");
else
Console.Write("Strings are "
+ "not rotations of each other");
}
}
// This code is contributed by nitin mittal.
PHP
0)
{
return true;
}
else
{
return false;
}
}
// Driver code
$str1 = "AACD";
$str2 = "ACDA";
if (areRotations($str1, $str2))
{
echo "Strings are rotations ".
"of each other";
}
else
{
echo "Strings are not " .
"rotations of each other" ;
}
// This code is contributed
// by Shivi_Aggarwal.
?>
Javascript
C++
#include
using namespace std;
bool check_rotation(string s, string goal)
{
if (s.size() != goal.size())
;
queue q1;
for (int i = 0; i < s.size(); i++) {
q1.push(s[i]);
}
queue q2;
for (int i = 0; i < goal.size(); i++) {
q2.push(goal[i]);
}
int k = goal.size();
while (k--) {
char ch = q2.front();
q2.pop();
q2.push(ch);
if (q2 == q1)
return true;
}
return false;
}
int main()
{
string s1 = "ABCD";
string s2 = "CDAB";
if (check_rotation(s1, s2))
cout << s2 << " is a rotated form of " << s1
<< endl;
else
cout << s2 << " is not a rotated form of " << s1
<< endl;
string s3 = "ACBD";
if (check_rotation(s1, s3))
cout << s3 << " is a rotated form of " << s1
<< endl;
else
cout << s3 << " is not a rotated form of " << s1
<< endl;
return 0;
}
Java
import java.util.*;
class GFG{
static boolean check_rotation(String s, String goal)
{
if (s.length() != goal.length())
;
Queue q1 = new LinkedList<>();
for (int i = 0; i < s.length(); i++) {
q1.add(s.charAt(i));
}
Queue q2 = new LinkedList<>();
for (int i = 0; i < goal.length(); i++) {
q2.add(goal.charAt(i));
}
int k = goal.length();
while (k>0) {
k--;
char ch = q2.peek();
q2.remove();
q2.add(ch);
if (q2.equals(q1))
return true;
}
return false;
}
public static void main(String[] args)
{
String s1 = "ABCD";
String s2 = "CDAB";
if (check_rotation(s1, s2))
System.out.print(s2+ " is a rotated form of " + s1
+"\n");
else
System.out.print(s2+ " is not a rotated form of " + s1
+"\n");
String s3 = "ACBD";
if (check_rotation(s1, s3))
System.out.print(s3+ " is a rotated form of " + s1
+"\n");
else
System.out.print(s3+ " is not a rotated form of " + s1
+"\n");
}
}
// This code is contributed by gauravrajput1
Python3
def check_rotation(s, goal):
if (len(s) != len(goal)):
skip
q1 = []
for i in range(len(s)):
q1.insert(0, s[i])
q2 = []
for i in range(len(goal)):
q2.insert(0, goal[i])
k = len(goal)
while (k > 0):
ch = q2[0]
q2.pop(0)
q2.append(ch)
if (q2 == q1):
return True
k -= 1
return False
if __name__ == "__main__":
s1 = "ABCD"
s2 = "CDAB"
if (check_rotation(s1, s2)):
print(s2, " is a rotated form of ", s1)
else:
print(s2, " is not a rotated form of ", s1)
s3 = "ACBD"
if (check_rotation(s1, s3)):
print(s3, " is a rotated form of ", s1)
else:
print(s3, " is not a rotated form of ", s1)
# This code is contributed by ukasp.
Javascript
C++
#include
#include
using namespace std;
bool checkString(string &s1, string &s2, int indexFound, int Size)
{
for(int i=0;i indexes; //store occurences of the first character of s1
int Size = s1.length();
char firstChar = s1[0];
for(int i=0;i
Javascript
Strings are rotations of each other
方法 2(使用 STL):
算法 :
1.如果两个字符串的大小不相等,那么永远不可能。
2. 将原始字符串推入队列q1 。
3. 将要检查的字符串推入另一个队列q2中。
4. 继续弹出q2并将其推回其中,直到此类操作的数量小于字符串的大小。
5. 如果在这些操作期间的任何时候q2等于q1 ,这是可能的。否则没有。
C++
#include
using namespace std;
bool check_rotation(string s, string goal)
{
if (s.size() != goal.size())
;
queue q1;
for (int i = 0; i < s.size(); i++) {
q1.push(s[i]);
}
queue q2;
for (int i = 0; i < goal.size(); i++) {
q2.push(goal[i]);
}
int k = goal.size();
while (k--) {
char ch = q2.front();
q2.pop();
q2.push(ch);
if (q2 == q1)
return true;
}
return false;
}
int main()
{
string s1 = "ABCD";
string s2 = "CDAB";
if (check_rotation(s1, s2))
cout << s2 << " is a rotated form of " << s1
<< endl;
else
cout << s2 << " is not a rotated form of " << s1
<< endl;
string s3 = "ACBD";
if (check_rotation(s1, s3))
cout << s3 << " is a rotated form of " << s1
<< endl;
else
cout << s3 << " is not a rotated form of " << s1
<< endl;
return 0;
}
Java
import java.util.*;
class GFG{
static boolean check_rotation(String s, String goal)
{
if (s.length() != goal.length())
;
Queue q1 = new LinkedList<>();
for (int i = 0; i < s.length(); i++) {
q1.add(s.charAt(i));
}
Queue q2 = new LinkedList<>();
for (int i = 0; i < goal.length(); i++) {
q2.add(goal.charAt(i));
}
int k = goal.length();
while (k>0) {
k--;
char ch = q2.peek();
q2.remove();
q2.add(ch);
if (q2.equals(q1))
return true;
}
return false;
}
public static void main(String[] args)
{
String s1 = "ABCD";
String s2 = "CDAB";
if (check_rotation(s1, s2))
System.out.print(s2+ " is a rotated form of " + s1
+"\n");
else
System.out.print(s2+ " is not a rotated form of " + s1
+"\n");
String s3 = "ACBD";
if (check_rotation(s1, s3))
System.out.print(s3+ " is a rotated form of " + s1
+"\n");
else
System.out.print(s3+ " is not a rotated form of " + s1
+"\n");
}
}
// This code is contributed by gauravrajput1
Python3
def check_rotation(s, goal):
if (len(s) != len(goal)):
skip
q1 = []
for i in range(len(s)):
q1.insert(0, s[i])
q2 = []
for i in range(len(goal)):
q2.insert(0, goal[i])
k = len(goal)
while (k > 0):
ch = q2[0]
q2.pop(0)
q2.append(ch)
if (q2 == q1):
return True
k -= 1
return False
if __name__ == "__main__":
s1 = "ABCD"
s2 = "CDAB"
if (check_rotation(s1, s2)):
print(s2, " is a rotated form of ", s1)
else:
print(s2, " is not a rotated form of ", s1)
s3 = "ACBD"
if (check_rotation(s1, s3)):
print(s3, " is a rotated form of ", s1)
else:
print(s3, " is not a rotated form of ", s1)
# This code is contributed by ukasp.
Javascript
CDAB is a rotated form of ABCD
ACBD is not a rotated form of ABCD
使用的库函数:
字符串:
strstr 在 string 中查找子字符串。
原型:char * strstr(const char *s1, const char *s2);
有关详细信息,请参阅 http://www.lix.polytechnique.fr/Labo/Leo.Liberti/public/computing/prog/c/C/MAN/strstr.htm
字符串:
strncat 连接两个字符串
原型:char *strcat(char *dest, const char *src);
有关详细信息,请参阅 http://www.lix.polytechnique.fr/Labo/Leo.Liberti/public/computing/prog/c/C/MAN/strcat.htm
时间复杂度:这个问题的时间复杂度取决于 strstr函数的实现。
如果 strstr 的实现是使用 KMP 匹配器完成的,那么上述程序的复杂度是 (-)(n1 + n2) 其中 n1 和 n2 是字符串的长度。 KMP 匹配器花费 (-)(n) 时间在长度为 n 的字符串中查找子字符串,其中假设子字符串的长度小于字符串。
方法三:
算法:
1.查找待检查字符串中原字符串第一个字符的所有位置。
2.对于找到的每个位置,将其视为要检查的字符串的起始索引。
3.从新的起始索引开始,比较两个字符串并检查它们是否相等。
(假设原始字符串为s1 ,待检查字符串为s2 ,n为字符串长度, j为 s1 的第一个字符在 s2 中的位置,
然后对于 i < (原始字符串的长度),检查是否 s1[i]==s2[(j+1)%n)。如果发现任何字符不匹配,则返回 false,否则返回 true。
4.对找到的所有位置重复第 3 步。
C++
#include
#include
using namespace std;
bool checkString(string &s1, string &s2, int indexFound, int Size)
{
for(int i=0;i indexes; //store occurences of the first character of s1
int Size = s1.length();
char firstChar = s1[0];
for(int i=0;i
Javascript
s2 is rotation of s1
时间复杂度:
在最坏的情况下,时间复杂度将是 n*n,其中 n 是字符串的长度。