一个程序来检查字符串是否是彼此的旋转?
在这里,我们将看到一个程序,它可以判断两个字符串是否互为旋转。字符串的旋转就像:
假设有两个字符串 S1 = ‘HELLO’,S2 = ‘LOHEL’ 因此它们互为旋转。将 HELLO 向左旋转三个位置,它将变成 LOHEL。
为了解决这个问题,我们将第一个字符串与自身连接起来,然后检查第二个字符串是否出现在连接后的字符串中。因此对于 HELLO,它将是 HELLOHELLO。然后这个连接后的字符串包含 LOHEL。[HELLOHELLO]。
算法
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
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP