一个检查字符串是否相互旋转的程序?
在这里,我们将看到一个程序,该程序可以判断两个字符串是否彼此旋转。字符串的旋转就像-
假设两个字符串是S1='HELLO'和S2='LOHEL',那么它们是彼此旋转的。将HELLO旋转到左侧三个位置,即为LOHEL。
为了解决这个问题,我们将第一个字符串与其自身连接起来,然后检查第二个字符串是否存在于连接的字符串中。因此,对于HELLO,将是HEL
算法
isRotation(str1,str2)
begin
if lengths of str1, and str2 are not same then return false;
temp := concatenate str1 with str1 itself
if temp contains str2, then
return true
otherwise return false
end示例
#include<iostream>
using namespace std;
bool isRotation(string str1, string str2){
if(str1.length() != str2.length())
return false;
string con_str = str1 + str1;
if(con_str.find(str2) != string::npos){
return true;
} else {
return false;
}
}
main() {
string str1, str2;
cout << "Enter two strings: ";
cin >> str1 >> str2;
if(isRotation(str1, str2)){
cout << "Two strings are rotation of each other";
} else {
cout << "Two strings are not rotation of each other";
}
}输出结果
Enter two strings: STACK CKSTA Two strings are rotation of each other
热门推荐
10 小红书平安祝福语简短
11 生日祝福语大全女孩简短
12 收生日红包祝福语 简短
13 领证幽默祝福语简短
14 法考面试祝福语简短
15 老哥出门祝福语简短语
16 送灯祝福语简短独特
17 幼儿狗年祝福语大全简短
18 好听的元旦简短祝福语